Chapter 14 - Worked Exercises 4

Exercise 1 - Sets

Write a template class that implements a set of items. A set is a collection of items where no items appear more than once.

You can use any method you know to internally store the items of the set (vectors, dynamic arrays, etc).

Part 1

The class should implement the following methods:

  • Set::add - Add a new item to the set. If the item is already in the set then nothing happens.

  • Set::remove - Remove an item from the set.

  • Set::size - Returns the number of items in the set

  • Set::contains - Returns true if an item is in the set, false otherwise

  • Set::elements - Returns a pointer to a dynamically allocation array containing each item in the set. The caller of the function is responsible for deallocating the array later.

Part 2

Test your class by creating different sets of different data types, i.e. a set of integers, a set of strings, etcetera.

Exercise 2 - Maps

A map is a data structure that maps certain keys to values.

Create a Map template class that requires two type parameters:

template <typename K, typename V>
class Map {
    // ...
};

Where the template parameters K and V correspond to the type of the keys and values to be stored.

For example if I were to store a map of employee ID numbers to employee names, I would create a Map<int, std::string>

Internally you may use any data structure to represent your map, e.g. two vectors, two arrays, etc.

Part 1

The class should have the following functionality:

  • Map::add(K key, V value) - Add a new key-value pair to the map

  • Map::set(K key, V value) - Set an existing key-value pair to a new value for a given key

  • Map::delete(K key) - Delete a key-value pair from the map for a given key

  • Map::contains(K key) - Checks if a key-value pair exists for a given key

  • Map::get(K key) - Retrieves the value for a key-value pair given the key

Part 2

Test your class by creating different sets of different data types.

Exercise 3 - Variadic Templates

In all of the below exercises, the variadic templates must be implemented recursively (there's no other way to do this!), meaning one template function for the base case, and one recursive case that unpacks towards the base case.

Part 1

Create a variadic template function that prints its arguments in reverse-order.

print_reverse(5.0, 4.0, 3.0, 2.0, 1.0);
// Prints 1.0, 2.0, 3.0, 4.0, 5.0 

Part 2

Create a variadic template function that returns the number of arguments that was passed into it:

auto num_args = count_args(5.0, 4, "Hello");
// Returns 3 

Part 3

Create a variadic template function that returns true if there are two subsequent arguments in the argument list with the same value, false otherwise:

auto result = has_matching_pair(1.0, 2.0, -1.0, 4.0, 8.0); 
// Returns false 

auto result2 = has_matching_pair(2.0, 1.5, 1.5, 6.0); 
// Returns true 

Last updated

Was this helpful?