Lab 13: templates, pair, and
vector
Exercise 1. swap box
I’ve placed a file SwapBox.hh in this repo. This the
start of the definition of a template class
SwapBox<T> that keeps track of a pair of values of
type T. It has a get method that always
returns the first component of that pair, and a set method
that allows a client to set only the first value of the pair. Finally,
it has a method swap that swaps the two elements in that
pair.
I’ve only given the class definition in this file, but I haven’t
written any of the method definitions. Write those. (Recall that,
because this is a template class, they need to be written within the
.hh file.) You can use the file Stck_T.hh as a
guide to the template method syntax.
The contents of a SwapBox<T> object is a
std::pair<T,T> object as defined in the C++ STL. It
has two components, a first of type T and a
second of type T.
I’ve also written code for a client that can be compiled with the
line
g++ -std=c++11 -o swap_int swap_int.cc
It builds an object and tests each of the methods.
Write a similar client swap_string.cc that tests a
SwapBox<std::string> object.
Exercise 2. odometer
I’ve included the definition of a Odometer class in a
file Odometer.hh. This defines an odometer object that is a
vector of digits between 0 and base-1. And
odometer can be reset which sets all of its digits to
0. It can be incremented, and that bumps the odometer up by
one. Below is a use of this class in the client
odom.cc:
% ./odom
Enter the width of your odometer: 3
Enter its base: 2
How many times would you like to advance it?
10
Okay. Here goes...
000
001
010
011
100
101
110
111
000
001
010
Here we have a binary odometer with three bits. And then we increment
it 10 times starting at 000. After eight “ticks” the
odometer wraps around to all 0s.
In a file named Odometer.cc write each of the methods
for this odometer class. Since we use a
std::vector<int> to represent the odometer, you might
find these features of vector useful:
vector<T>(void): this constructor builds a vector
of size 0.
resize(int sz): this sets a vector to a certain
size.
size(void): this gives the number of components of the
vector.
at(int i): this accesses the i-th
component of the vector.
for (int x: v) ... : you can iterate over the elements
x of a std::vector<int> v.