These exercises provide practice with using and defining template functions and classes.
#include <iostream> #include <vector> using namespace std; template <typename Item> class stack { vector<Item> v; public: bool empty() const { return v.size() == 0; } void push(const Item & x) { v.push_back(x); } void pop() { v.pop_back(); } // It takes two... Item & top() { return v.back(); } const Item & top() const { return v.back(); } }; int main() { stack<int> si; si.push(1); si.push(2); si.push(3); while (! si.empty()) { cout << si.top(); si.pop(); } return 0; } |
Write a generic queue class based on list and test it.
You will need a map from strings to integers to keep track of the number of occurrences of each word.
HINT: Because there is as yet no easy way to get all the words in a map, you will also need to maintain a vector or list of all the words seen (but only one of each). (Next session we will cover iterators, which can be used instead.)
HINT: You will need a new class to hold the statistics for a word (a pair of two ints? BTW, pair is defined inside utility), and then a map from words to objects of this class.