Skip to content

Word List

BrandonRobare edited this page Jun 2, 2026 · 1 revision

Word List

Folder: 02-word-list

What it is

A WordList reads a file and counts how many times each word appears. It stores the counts in a dynamic array that I grow by hand, one slot at a time. The point of the lab is the rule of three: because the class owns a raw WordOccurrence*, it needs a copy constructor, a destructor, and an overloaded assignment operator so copies do not share or leak the buffer.

How this code does it

Two classes carry the work. WordOccurrence holds a single word and its count, with matchWord to test equality and increment to bump the count. WordList owns the array.

addWord is the core. It scans the array for the word. If the word is already there it calls increment. If not, it allocates a fresh array one element larger, copies the old contents over, appends the new word with count 1, deletes the old array, and swaps the pointer. So every new distinct word costs a full copy of the array, which is quadratic over a document but keeps the memory management explicit.

sort orders the array by count, breaking ties alphabetically, through a lambda passed to std::sort. The main in wordListMain.cpp strips punctuation and lowercases each token before adding it, so the count is case insensitive.

The three special members all do the same dance: release the current buffer, then deep-copy the other object's buffer. The assignment operator guards against self-assignment first.

Structure

classDiagram
    class WordOccurrence {
        -string word_
        -int num_
        +matchWord(string) bool
        +increment() void
        +getWord() string
        +getNum() int
    }
    class WordList {
        -WordOccurrence* wordArray_
        -int size_
        +WordList()
        +WordList(const WordList&)
        +~WordList()
        +operator=(const WordList&) WordList&
        +addWord(string) void
        +sort() void
        +print() void
    }
    WordList o-- "0..*" WordOccurrence : owns a dynamic array of
Loading

Build and run

g++ -std=c++17 02-word-list/wordListMain.cpp -o wordCount
./wordCount file1.txt

The folder also ships a Makefile and sample input and expected-output text files.

Notes

This is my implementation built against a header the course provided. The growth strategy is deliberately naive so the allocation and copy are easy to see; a real container would double its capacity to amortize the cost.

Clone this wiki locally