Week 4 Wednesday Tutorial Exercises

1. The sum.h file contains the sum() template function from today's lecture, and the test_sum.cc file contains the tests of sum() from today's lecture. Compile the test_sum.cc file and observe it crash. Modify the sum() function so that it works by taking a constant reference to the object which should be considered "zero" for the purposes of the summation. In particular, make the function definition be
template <typename T>
T sum(const vector<T> &v, const T &zero = 0);

and then make the local variable result be initialised to the value of zero. Notice that the default value for zero means that sum() can still be called in the same way as before the modification. Compile and run test_sum.cc and notice that it still crashes. Now modify test_sum.cc so that sum(vs) is instead sum(vs, string()). Compile and run test_sum.cc and verify that it now works.

2. Modify your List class from last Wednesday's tutorial so that it is a fully templated class which can be used to store values of any type. Also modify the test program so that it tests the List class with at least two different types.

3. Implement some template functions that use iterators and containers (similar to the final version of the find() function from today's lecture) and check that they work with the different containers looked at in the lectures. For example:
• Write a template function called double_copy which is passed two input iterators and a reference to an ostream, and outputs each element in the input range to the ostream but doubles it first (ie. multiplies it by 2)... You can test it like so:
int main() {
vector<int> v;
for (int i = 1; i <= 10; ++i)
v.push_back(i);
double_copy(v.begin(), v.end(), std::cout);
}

4. Write a simple Array template class. It should be a simple wrapper around normal C++ style arrays, but it should also keep track of the size of the array and return the size with a size() method. It shouldn't do any bounds-checking, that is, there is no need to check whether or not an element being accessed is valid (ie. between 0 and size() - 1) or not. To allow the Array objects to use indexing as for normal C++ arrays, you should use the operator[] which can be defined as followed:
T &operator[](size_t i);

and should return a reference to the i-th element of the Array object.

Your class should be usable as follows:

#include "Array.h"
#include <iostream>

int main() {
Array<int> a(10);
for (int i = 0; i < a.size(); i++)
a[i] = i + 1;

Array<int> b = a;
for (int i = 0; i < a.size(); i++)
b[i] *= 2;

for (int i = 0; i < a.size(); i++)
std::cout << a[i] << " " << b[i] << std::endl;

Array<const char*> s(3);
s = "one";
s = "two";
s = "three";
for (int i = 0; i < s.size(); i++)
std::cout << s[i] << std::endl;
}