Chapter 3 Exercises

Exercise 3.1: Vectors and strings

Imagine you are writing a program to manage a shopping list. Each shopping list item is represented by a string stored in a container. Your design requires a print function that prints out the contents of the shopping list.

Using a vector to hold the shopping list items, write a print function to print out the contents of a vector of strings. Test your print function with a main program that does the following:

  1. Create an empty vector. Print it.
  2. Append the items, "eggs," "milk," "sugar," "chocolate," and "flour" to the list. Print it.
  3. Remove the last element from the vector. Print it.
  4. Append the item, "coffee" to the vector. Print it.
  5. Write a loop that searches for the item, "sugar" and replace it with "honey." Print the vector.
  6. Write a loop that searches for the item, "milk," and then remove it from the vector. (You are permitted to reorder the vector to accomplish the removal, if you want.) Print the vector.
  7. Search for the item, "milk" and find a way to remove it without changing the order of the rest of the vector. (This is not necessarily an efficient operation.) Print the vector one more time.

Chapter 4 Exercises

Exercise 4.1: Using lists

In Exercise 3.1, you wrote a small part of a shopping-list management program using vectors. Now we'll switch to using list instead of vector for the shopping list.

  1. Copy your solution from Exercise 3.1. Globally replace every occurrence of vector with list. Try to compile it. Why doesn't it compile?
  2. Rewrite the print function and main program so that they will work for the list-based shopping list. Run the new program.

Exercise 4.2: Inserting and removing list elements

Modify the main program from Exercise 4.1 to do the following:

  1. Create an empty list.
  2. Append the items, "eggs," "milk," "sugar," "chocolate," and "flour" to the list. Print the list.
  3. Remove the first element from the list. Print the list.
  4. Insert the item, "coffee" at the beginning of the list. Print the list.
  5. Find the item, "sugar" and replace it with "honey." Print the list.
  6. Insert the item, "baking powder" before "milk" in the list. Print the list.

Chapter 5 Exercises

Exercise 5.1: Simple stream I/O

Using the print function from Exercises 4.1 and 4.2, write a main program that prompts the user for a shopping list item, and then reads a string and inserts it into a list in alphabetical order. The program should loop until the user enters done. Print the resulting list using the print function.

Make sure that your program is capable of handling entries like "Cheddar cheese" and that it doesn't go into an endless loop if you enter the end-of-file character (Ctrl+z on DOS and MS Windows, Ctrl+d on UNIX).

Exercise 5.2: String manipulations

Write a program that initializes a string with the following text:

Congratulations Mrs. <name>, you and Mr. <name> are the lucky recipients of a trip for two to XXXXXX. Your trip to XXX is already scheduled.

Use string functions to perform the following manipulations:

  1. Replace every occurrence of "<name>" with "Luzer."
  2. Replace every occurrence of "XXX," regardless of the number of Xs, with "Siberia."
  3. Insert the letters "un" before the first occurrence of the word "luck."
  4. Append the words "for December" to the string.
  5. Print the resulting string.

Chapter 6 Exercises

Exercise 6.1: Algorithms

Using both the print function from Exercise 3.1 (vector-based shopping list) and the print function from Exercise 4.1 (list-based shopping list), write a main program to perform the following manipulations (the print functions will be overloaded on different argument types, so they will not conflict):

  1. Create an empty list.
  2. Append the items, "eggs," "milk," "sugar," "chocolate," and "flour" to the list. Print the list.
  3. Use the copy algorithm to copy the contents of the list to a vector. Print the vector.
  4. Use the sort algorithm to sort the vector. Print the vector.

Exercise 6.2: Function objects

Beginning with your solution to Exercise 6.1, add the following steps to your main program:

  1. Use the sort algorithm and the greater<T> function object template to sort the vector in descending order. Print the vector.
  2. Use the count_if algorithm with a binder to count the number of elements that come before "flour" in alphabetical order. Print the result. Apply this solution to both the list and the vector. Do you get the same results?
  3. Create your own function object. Use it in conjunction with count_if to count the number of elements that contain exactly five letters.

Exercise 6.3: Sets

A building security system has door locks that are opened by typing a four-digit access code into a keypad. The access code is validated by querying an Access object with the following interface:

class Access
{
public:
  void activate(unsigned code);
  void deactivate(unsigned code);
  bool isactive(unsigned code) const;
};

Each employee is given a different access code, which is activated using the activate() function. When an employee leaves the company, his or her access code is deactivated using the deactivate() function.

Implement the Access class specified above. Write a test program that does the following:

  1. Create an Access object.
  2. Activate the codes 1234, 9999, and 9876.
  3. Prompt the user for an access code. Read the code from the console.
  4. Tell the user whether the door opened successfully.
  5. Repeat the last two steps until the door opens.
  6. Deactivate code that worked. Also, deactivate code 9999 and activate code 1111.
  7. Repeat steps 3 and 4 until the door opens.

Exercise 6.4: Maps

The customer that uses the security system described in the previous exercise now wants to associate an access level with each access code. Users with high access levels can open doors to more security-sensitive parts of the building than users with lower access levels. Begin with your solution to the previous exercise. Modify the Access class from the previous exercise so that an integer access level is associated with each code. The new interface should be as follows:

class Access
{
public:
  void activate(unsigned code, unsigned level);
  void deactivate(unsigned code);
  bool isactive(unsigned code, unsigned level) const;
};

The isactive() function returns true if the specified access code has an access level greater than or equal to the specified access level. (Of course, it should return false if the access code is not active at all.) Modify the main program to do the following:

  1. Create an Access object.
  2. Activate code 1234 with access level 1, code 9999 with access level 5, and code 9876 with access level 9.
  3. Prompt the user for an access code. Read the code from the console.
  4. Assuming a door that requires access level 5 for entry, tell the user whether the door opened successfully.
  5. Repeat the last two steps until the door opens.
  6. Deactivate the code that worked. Change the access level of code 9999 to 8. Activate code 1111 with access level 7.
  7. Prompt the user for an access code. Read the code from the console.
  8. Assuming a door that requires access level 7 for entry, tell the user whether the door opened successfully.
  9. Repeat the last two steps until the door opens.

Chapter 7 Exercises

Exercise 7.1: Deques

A company that provides a special service for wind surfers installs wind gauges at popular windsurfing locations. Each gauge reports the current wind speed to a central computer every five minutes. When a user connects to the service she or he is able to retrieve recent high, low, and average wind speeds for her or his selected location. (A service like this really exists! It’s called the Wind Hot Line.)

The central computer creates a WindGauge object for each gauge. The WindGauge class interface looks as follows:

class WindGauge
{
public:
  WindGauge(int period = 12);
  void currentWindSpeed(int speed);
  int high() const;
  int low() const;
  int average() const;
private:
  // (exercise for the student)
};

The constructor argument specifies how much history is retained by the object (default 12 periods == 1 hour). When currentWindSpeed() is called, the current wind speed is added to the history. If the history is then longer than the specified period, the oldest wind speed is discarded. The other three functions return the highest, lowest, and average wind speeds reported during the history period.

Implement the WindGauge class as specified above. Write a dump function that prints out the low, high, and average wind speed for a WindGauge's data. Write a test program that does the following:

  1. Create a WindGauge.
  2. Add five wind speeds: 15, 16, 12, 15, and 15, and then dump the gauge.
  3. Add ten more measurements: 16, 17, 16, 16, 20, 17, 16, 15, 16, and 20 (bringing the total to over 12) and dump the numbers again.

Exercise 7.2: I/O manipulators

A program that generates the table of contents for books stores the contents in a map<int, string>, where the key is the page number and the string is the chapter name. (The key must be the page number so that the chapters are sorted in page-number order.) Each element of this map must be printed in the following format:

Chapter one.................................................  1
Chapter two................................................. 23

The chapter name is left-justified and padded with periods to 60 columns. The page number is right-justified and padded to three digits with spaces.

Write a program that does the following:

  1. Create a std::map<int, std::string>. Fill it with the following pairs: (1, "Introduction"), (9, "Chapter 1: Introducing TinyPIM"), (30, "Chapter 2: Implementing the Address Class with Text String") and (57, "Chapter 3: Creating the Address Book Using Container Classes").
  2. Iterate through each element of the map and print out the table of contents entry, using I/O manipulators to get the output into the format described above.

Chapter 8 Exercises

Exercise 8.1: User-defined algorithms

Copy your solution from Exercise 6.1 (or get a fresh version from the Web page). Merge the two print functions into a single template function that works like a standard algorithm. Modify the main program to use the new print interface. Add one line to the main program to print the vector, omitting the first and last elements.

Chapter 9 Exercises

Exercise 9.1: User-Defined I/O

A scientific graphing system needs to represent points on a two-dimensional plain using x, y coordinates (known as Cartesian coordinates). The following data class is used for this representation:

class point
{
public:
  point() : x_(0.0), y_(0.0) { }
  point(double x, double y) : x_(x), y_(y) { }
  double x() const { return x_; }
  double y() const { return y_; }
private:
  double x_, y_;
};

A point is represented textually as (x, y). For example (-1.5, 6.0) represents a point one-and-one-half units to the left and six units up from the origin, (0, 0). Implement stream input and output operators (operator>> and operator<<) for the point class. (Implementation hint for the input operator: To modify a point object, you need to create a new point and assign it to the old one.) Test your functions with the following test program:

int main()
{
  point p;

  while (std::cin.good())
  {
    std::cout << "Enter point as (x, y): ";
    if (std::cin.peek() == 'q')
      break;  // Quit program

    if (std::cin >> p)
    {
      std::cout << "You entered: **" << std::setfill('*')
                << std::setw(15) << std::left << p << std::endl;
    }
    else if (! std::cin.bad() && ! std::cin.eof())
    {
      std::cin.clear();
      std::cout << "Bad input" << std::endl;
    }
    std::cin.ignore(10000, '\n');
  } // end while

  return 0;
}