Exercise Sheet 5

IN3013/INM173 - Object Oriented Programming in C++

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.

  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 integers.

  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.

  5. Redo an exercise from last week: 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.