| CS 202 Fall 2013 > In-Class Challenge for Tuesday, November 5, 2013 |
CS 202 Fall 2013
In-Class Challenge for Tuesday, November 5, 2013
Our Goal
We wish to write a class template WaitInLine.
This keeps track of a “line”, like the one
for a cash register at a store.
You enter the line at the back and exit at the front,
so that people exit the line in the same order they entered.
An object of class WaitInLine<T>
should keep track of a “line”
of items of type T.
I will refer to type T as the value type.
WaitInLine
should have three public member functions.
put. Take a value whose type is the value type. Returns nothing. Enters its parameter at the back of the line.get. Takes no parameters. Returns the value type. Removes the value at the front of the line and returns it.empty. Takes no parameters. Returnsbool. Returnstrueif there are no items in the line; otherwise returnsfalse.
In addition,
WaitInLine should have a default constructor.
However, there is a good chance that you do not need to write it.
Example usage:
[C++]
WaitInLine<int> w; bool b1 = w.empty(); // Should be true w.put(8); bool b2 = w.empty(); // Should be false cout << w.get() << endl; // Prints 8 bool b3 = w.empty(); // Should be true w.put(6); w.put(42); w.put(-17); cout << w.get() << endl; // Prints 6 cout << w.get() << endl; // Prints 42 w.put(3); cout << w.get() << endl; // Prints -17 cout << w.get() << endl; // Prints 3
Class template WaitInLine
should be implemented in header waitinline.h.
Since this is a template, there is no associated source file.
What to Do
- Write class template
WaitInLine, in filewaitinline.h, as above. The resulting code should compile and pass all tests intest_waitinline.cpp.
Other Stuff
- Get things to compile first!
- Don’t forget “
const”. - Don’t worry about what member function
getdoes if the line is empty. We will leave it up to the caller to ensure thatgetis never called on an empty line. vectorhas memberspush_backandpop_back, but there are no correspondingpush_frontandpop_frontfor the other end. However, you can do the operation we would wantpop_frontto do using the following (here,vis avector).[C++]
v.erase(v.begin());
Note: This code uses iterators, which we will look at during the next class meeting.
- There is a standard name for a structure
that handles data in a first-in-first-out manner,
like
WaitInLine. It is called a queue (pronounced like the letter “Q”). - By the way,
the above design for class template
WaitInLineis flawed; it does not allow for proper error handling. We will discuss this in the next class meeting as well.