Module 07 Solutions
Exercise 00: swap, min, max
Section titled “Exercise 00: swap, min, max”Simple function templates.
template <typename T>void swap(T& a, T& b) { T temp = a; a = b; b = temp;}
template <typename T>T const& min(T const& a, T const& b) { return (a < b) ? a : b; // Return second if equal}
template <typename T>T const& max(T const& a, T const& b) { return (a > b) ? a : b; // Return second if equal}Exercise 01: iter
Section titled “Exercise 01: iter”Apply function to each element.
template <typename T>void iter(T* array, size_t length, void (*func)(T&)) { for (size_t i = 0; i < length; i++) func(array[i]);}
// Const versiontemplate <typename T>void iter(T* array, size_t length, void (*func)(T const&)) { for (size_t i = 0; i < length; i++) func(array[i]);}template <typename T>void print(T const& elem) { std::cout << elem << std::endl;}
int main() { int arr[] = {1, 2, 3, 4, 5}; iter(arr, 5, print<int>); // Must specify type}Exercise 02: Array Class Template
Section titled “Exercise 02: Array Class Template”Full class template with bounds checking.
template <typename T>class Array {private: T* _array; unsigned int _size;
public: Array() : _array(NULL), _size(0) {}
Array(unsigned int n) : _array(new T[n]()), _size(n) {}
Array(const Array& other) : _array(NULL), _size(0) { *this = other; }
Array& operator=(const Array& other) { if (this != &other) { delete[] _array; _size = other._size; _array = new T[_size]; for (unsigned int i = 0; i < _size; i++) _array[i] = other._array[i]; } return *this; }
~Array() { delete[] _array; }
T& operator[](unsigned int index) { if (index >= _size) throw std::out_of_range("Index out of bounds"); return _array[index]; }
const T& operator[](unsigned int index) const { if (index >= _size) throw std::out_of_range("Index out of bounds"); return _array[index]; }
unsigned int size() const { return _size; }};Key Points:
- Template implementation must be in header
new T[n]()value-initializes elements- Deep copy in both copy constructor and assignment
- Bounds checking with exception