The WordArrayT
Objectives
We would like to :- Implement a static array to hold words.
Notes
- We discussed a static array of WordCountT in our initial design
- Data:
- size_t size, capacity
- WordCountT data[MAX_WORDS]
- Methods:
- constructor
- Size - to get the current elements
- Capacity - to get the capacity
- PushBack(WordCountT) to add a word
- [] to access the array
- at to access the array
- Take a look at WordArrayT.h.
- Note:
using DataT = WordCountT;- This makes
DataTa nickname forWordCountT - This makes it generic so I can change the data type by changing this line.
- This is the modern form
- it could also be done with
typedef WordCountT DataT;, but you should use the other form. - It could also be done with a
#defineBUT DO NOT DO THAT.
- This makes
- Note I declare MAX_WORDS outside of the class.
- Note I perform most of the initialization in the declaration
- I really don't need a constructor because of this.
- The compiler will write one for me.
- Which will be the default constructor, which does nothing.
- Note:
- The implementation of [] is interesting
- There are two forms
- One that returns a constant reference.
- One that returns a reference.
- There are two forms
- The constant reference
- This is for the right hand side (RHS).
-
WordArrayT words; WordCountT word; ... word = words[3];
- It gives me back an array entry that I will not change.
- The prototype is
const DataT & operator [] (size_t index) const - You could also use the modern
constexpr, but I have not yet learned that. - The function just returns the data at the index.
- This is dangerous, but convention says it is the user's responsibility to get the index right.
- The RHS
at- Same semantics
- But checks to see if the index is valid.
- We have a problem here, what do we return if the index is not valid?
- For now we will return data[0], but this is bad.
- Later we will learn about exceptions, which is what we should do here.
- The reference (or left hand side, LHS);
-
WordArrayT words; WordCountT word; ... words[3] = word;
- This allows us to change an element in the array.
- The prototype is
DataT & operator [] (size_t index);.
-
- The LHS at function is the same.
- Surprisingly these functions are duplicates here, but perhaps not for other structures.
- Data:
- See WordArrayT.cpp.