Programming in C++

Exercise Sheet 5

These exercises provide further practice with defining and using generic classes, this time using STL iterators.

  1. Write a function to print out the elements of a list, by obtaining an iterator from the list, and using it to step through the elements. Test your function by creating an empty list, pushing some elements onto it and using your function to print it.

    Use this example05.cc file as a starting point - it shows how this is done with vectors, using three different ways. Lists support only the last two. Try to implement both versions for list (old C++ with explicit iterator types and C++11 with auto).

    The second function inside example05.cc has three for loops - the first two are wrong, only the last one is correct. Try uncommenting each of the wrong ones to see what error message you get - try to understand that error message (you'll get quite a few of those on your code!).

  2. An iterator returns the elements of the container by reference, so it is possible to update them (just as when dereferencing a pointer). Write a function to update a list of integers, by doubling each element.

  3. Generalize the previous function to a template function to double the elements of any container of numbers. So it should work for a vector<int>, vector<double>, list<float>, etc.

  4. Each sequence (including list, deque and vector) has a constructor taking two iterator arguments, where the second can be reached by incrementing the first. For example, these might be the begin() and end() of some other container. Use this to initialize a vector as a copy of a list. See here for the constructors of vector -- it's the third one ("range") we're looking for.

  5. Redo an exercise from last session: Write a program that reads words from the standard input and when the input is reached prints out each word once, with a count of the number of times it occurred in the input. As before you will need a map from strings to integers to keep track of the number of occurrences of each word, but you will not need any extra structure to keep track of the words – you can iterate over the map.