13.9 Programming Exercises
Exercise 13-1: Write a parity class. The class supplies a member function named
put, which counts the number of elements supplied.
The other member function test returns
true if an even number of
put calls have been made and false
otherwise.
Member functions:
void parity::put( ); // Count another element
bool parity::test( ); // Return true if an even number of
// puts have been done. Return false
// for an odd number.
Exercise 13-2: Write a "checkbook" class. You put
a list of numbers into this class and get a total out.
Member functions:
void check::add_item(int amount); // Add a new entry to the checkbook
int check::total( ); // Return the total of all items
Exercise 13-3: Write a class to implement a simple queue. A queue is similar to a
stack except that the data is removed in first-in-first-out (FIFO)
order.
Member functions:
void queue::put(int item); // Insert an item in the queue
int queue::get( ); // Get the next item from the queue
Sample usage:
queue a_queue;
a_queue.put(1); // Queue contains: 1
a_queue.put(2); // Queue contains: 1 2
a_queue.put(3); // Queue contains: 1 2 3
std::cout << a_queue.get( ) << '\n'; // Prints 1, queue contains 2 3
std::cout << a_queue.get( ) << '\n'; // Prints 2, queue contains 3
Exercise 13-4: Define a class that will hold the set of integers from 0 to 31. An
element can be set with the set member function
and cleared with the clear member function. It is
not an error to set an element that's already set or
clear an element that's already clear. The function
test is used to tell whether an element is set.
Member functions:
void small_set::set(int item); // Set an element in the set
void small_set::clear(int item); // Clear an element in the set
int small_set::test(int item); // See whether an element is set
Sample usage:
small_set a_set;
a_set.set(3); // Set contains [3]
a_set.set(5); // Set contains [3,5]
a_set.set(5); // Legal (set contains [3,5])
std::cout << a_set.test(3) << '\n'; // Prints "1"
std::cout << a_set.test(0) << '\n'; // Prints "0"
a_set.clear(5); // Set contains [3]
Exercise 13-5: I have a simple method of learning foreign vocabulary words. I write
the words down on flash cards. I then go through the stack of cards
one at a time. If I get a word right, that card is discarded. If I
get it wrong, the card goes to the back of the stack.
Write a class to implement this system.
Member functions:
struct single_card {
std::string question; // English version of the word
std::string answer; // Other language version of the word
};
// Constructor -- takes a list of cards to
// initialize the flash card stack
void flash_card::flash_card(single_card list[]);
// Get the next card
const single_card& flash_card::get_card( );
//The student got the current card right
void flash_card::right( );
// The student got the current card wrong
void flash_card::wrong( );
//Returns true -- done / false -- more to do
bool done( );
|