Description
The purpose of this challenge is to use class templates.
Requirements
- Write a class template called Collection.
template <class T> class Collection { private: T * data; int max; public: Collection(int size, T initial_value) { max = size; // initialize data as an array of size max // fill the array with initial_value } };
- Create a destructor to dispose of the data array.
- Create a public function, int count(T value). This function returns the number of occurrences of value in the data array.
- Create a public function, bool contains (T value). This function returns true or false if value is found in the data array.
- Create an overloaded operator for the subscript operator, [].
T& operator[](int index) { // return the value in data at the index subscript location }
- Create the prototype of a public member function, T at(int index); Similar to step 5, this function simply returns the value in data at index. Write this function so that it will also throw an out_of_range(“Index exceeds collection size”) exception. Write the definition of this function outside the class definition body, rather than inline.
// when defining outside of class body, you need to add // template specification and class resolution T& at(int index) { if (some condition) throw out_of_range("Index exceeds collection size"); // return the value in data at the index subscript location }
- In main, write driver code to exercise each of the various public functions in the Collection class. Make sure to access the object’s data elements using the subscript operator — this exercises the overloaded [] operator.
Sample main()
int main() { Collection <int> info(10, 0); // write driver code here // this tests subscript operator info[0] = 100; // also try creating objects of different types as well Collection <string> text(5, "N/A"); return 0; }
CATALOG ID: CPP-CHAL00046
Print Requirements