Thinking in C++ Vol 2 - Practical Programming |

Prev |
Home |
Next |

Solutions
to selected exercises can be found in the electronic document *The Thinking
in C++ Volume 2 Annotated Solution Guide*, available for a small fee from *www.MindView.net*.

1. Create a generator that returns the current value of **clock( )**
(in **<ctime>**). Create a **list<clock_t>**, and fill it
with your generator using **generate_n( )**. Remove any duplicates in
the list and print it to **cout** using **copy( )**.

2. Using **transform( )** and **toupper( )** (in **<cctype>**),
write a single function call that will convert a string to all uppercase
letters.

3. Create a **Sum** function object template that will accumulate
all the values in a range when used with **for_each( )**.

4. Write an anagram generator that takes a word as a command-line
argument and produces all possible permutations of the letters.

5. Write a sentence anagram generator that takes a sentence as a
command-line argument and produces all possible permutations of the words in
the sentence. (It leaves the words alone and just moves them around.)

6. Create a class hierarchy with a base class **B** and a derived
class **D**. Put a **virtual** member function **void f( )** in **B**
such that it will print a message indicating that **B** s **f( )**
was called, and redefine this function for **D** to print a different
message. Create a **vector<B*>**, and fill it with **B** and **D**
objects. Use **for_each( )** to call **f( )** for each of the
objects in your **vector**.

7. Modify **FunctionObjects.cpp** so that it uses **float**
instead of **int**.

8. Modify **FunctionObjects.cpp** so that it templatizes the main
body of tests so you can choose which type you re going to test. (You ll have
to pull most of **main( )** out into a separate template function.)

9. Write a program that takes an integer as a command line argument
and finds all of its factors.

10. Write a program that takes as a command-line argument the name of
a text file. Open this file and read it a word at a time (hint: use **>>**).
Store each word into a **vector<string>**. Force all the words to
lowercase, sort them, remove all the duplicates, and print the results.

11. Write a program that finds all the words that are in common
between two input files, using **set_intersection( )**. Change it to
show the words that are not in common, using **set_symmetric_difference( )**.

12. Create a program that, given an integer on the command line,
creates a factorial table of all the factorials up to and including the
number on the command line. To do this, write a generator to fill a **vector<int>**,
and then use **partial_sum( )** with a standard function object.

13. Modify **CalcInventory.cpp** so that it will find all the
objects that have a quantity that s less than a certain amount. Provide this
amount as a command-line argument, and use **copy_if( )** and **bind2nd( )**
to create the collection of values less than the target value.

14. Use **UrandGen( )** to generate 100 numbers. (The size of
the numbers does not matter.) Find which numbers in your range are congruent
mod 23 (meaning they have the same remainder when divided by 23). Manually pick
a random number yourself, and determine whether that number is in your range by
dividing each number in the list by your number and checking if the result is 1
instead of just using **find( )** with your value.

15. Fill a **vector<double>** with numbers representing
angles in radians. Using function object composition, take the sine of all the
elements in your **vector** (see **<cmath>**).

16. Test the speed of your computer. Call **srand(time(0))**, then
make an array of random numbers. Call **srand(time(0))** again and generate
the same number of random numbers in a second array. Use **equal( )**
to see if the arrays are the same. (If your computer is fast enough, **time(0)**
will return the same value both times it is called.) If the arrays are not the
same, sort them and use **mismatch( )** to see where they differ. If
they are the same, increase the length of your array and try again.

17. Create an STL-style algorithm **transform_if( )**
following the first form of **transform( )** that performs
transformations only on objects that satisfy a unary predicate. Objects that
don t satisfy the predicate are omitted from the result. It needs to return a
new end iterator.

18. Create an STL-style algorithm that is an overloaded version of **for_each( )**
which follows the second form of **transform( )** and takes two input
ranges so it can pass the objects of the second input range a to a binary
function that it applies to each object of the first range.

19. Create a **Matrix** class template that is made from a **vector<vector<T>
>**. Provide it with a friend **ostream&
operator<<(ostream&, const Matrix&)** to display the matrix.
Create the following binary operations using the STL function objects where
possible: **operator+(const Matrix&, const Matrix&)** for matrix
addition, **operator*(const Matrix&, const vector<int>&)** for
multiplying a matrix by a **vector**, and **operator*(const Matrix&,
const Matrix&)** for matrix multiplication. (You might need to look up
the mathematical meanings of the matrix operations if you don t remember them.)
Test your **Matrix** class template using **int** and **float**.

20. Using the characters

"~`!@#$%^&*( )_-+=}{[]|\:;"'<.>,?/",

generate a codebook using an input file given on the command line as a
dictionary of words. Don t worry about stripping off the non-alphabetic
characters nor worry about case of the words in the dictionary file. Map each
permutation of the character string to a word such as the following:

"=')/%[}]|{*@?!"`,;>&^-~_:$+.#(<\" apple

"|]\~>#.+%(/-_[`':;=}{*"$^!&?),@<" carrot

"@=~['].\/<-`>#*)^%+,";&?!_{:|$}(" Carrot

etc.

Make sure that no duplicate codes or words exist in your code
book. Use **lexicographical_compare( )** to perform a sort on the
codes. Use your code book to encode the dictionary file. Decode your encoding
of the dictionary file, and make sure you get the same contents back.

21. Using the following names:

Jon Brittle

Jane Brittle

Mike Brittle

Sharon Brittle

George Jensen

Evelyn Jensen

Find all the
possible ways to arrange them for a wedding picture.

22. After being separated for one picture, the bride and groom
decided they wanted to be together for all of them. Find all the possible ways
to arrange the people for the picture if the bride and groom (Jon Brittle and
Jane Brittle) are to be next to each other.**</#><#TIC2V2_CHAPTER8_I350>**

23. A travel company wants to find out the average number of days
people take to travel from one end of the continent to another. The problem is
that in the survey, some people did not take a direct route and took much
longer than is needed (such unusual data points are called outliers ). Using
the following generator, generate travel days into a **vector**. Use **remove_if( )**
to remove all the outliers in your **vector**. Take the average of the data
in the **vector** to find out how long people generally take to travel.

int travelTime() {

// The "outlier"

if(rand() % 10 == 0)

return rand() % 100;

// Regular route

return rand() % 10 + 10;

}

** </#><#TIC2V2_CHAPTER8_I353>**

24. Determine how much faster **binary_search( )** is to **find( )**
when it comes to searching *sorted* ranges.</#><#TIC2V2_CHAPTER8_I354>

25. The army wants to recruit people from its selective service
list. They have decided to recruit those that signed up for the service in 1997
starting from the oldest down to the youngest. Generate an arbitrary amount of
people (give them data members such as **age** and **yearEnrolled**) into
a **vector**. Partition the **vector** so that those who enrolled in 1997
are ordered at the beginning of the list, starting from the youngest to the
oldest, and leave the remaining part of the list sorted according to age.

26. Make a **class** called **Town** with population, altitude,
and weather data members. Make the weather an **enum** with **{ RAINY,
SNOWY, CLOUDY, CLEAR }**. Make a class that generates **Town** objects.
Generate town names (whether they make sense or not it doesn t matter) or pull
them off the Internet. Ensure that the whole town name is lower case and there
are no duplicate names. For simplicity, we recommend keeping your town names to
one word. For the population, altitudes, and weather fields, make a generator
that will randomly generate weather conditions, populations within the range
[100 to 1,000,000) and altitudes between [0, 8000) feet. Fill a **vector**
with your **Town** objects. Rewrite the **vector** out to a new file
called **Towns.txt**.

27. There was a baby boom, resulting in a 10% population increase in
every town. Update your town data using **transform( )**, rewrite your
data back out to file.

28. Find the towns with the highest and lowest population. For this
exercise, implement **operator<** for your **Town** class. Also try
implementing a function that returns **true** if its first parameter is less
than its second. Use it as a predicate to call the algorithm you use.

29. Find all the towns within the altitudes 2500-3500 feet inclusive.
Implement equality operators for the **Town** class as needed.

30. We need to place an airport in a certain altitude, but location
is not a problem. Organize your list of towns so that there are no duplicate
(duplicate meaning that no two altitudes are within the same 100 ft range. Such
classes would include [100, 199), [200, 199), etc. altitudes. Sort this list in
ascending order in at least two different ways using the function objects in **<functional>**.
Do the same for descending order. Implement relational operators for **Town**
as needed.

31. Generate an arbitrary number of random numbers in a stack-based
array. Use **max_element( )** to find the largest number in array. Swap
it with the number at the end of your array. Find the next largest number and
place it in the array in the position before the previous number. Continue
doing this until all elements have been moved. When the algorithm is complete,
you will have a sorted array. (This is a selection sort .)

32. Write a program that will take phone numbers from a file (that
also contains names and other suitable information) and change the numbers that
begin with 222 to 863. Be sure to save the old numbers. The file format is as
follows:

222 8945

756 3920

222 8432

etc.

33. Write a program that, given a last name, will find everyone with
that last name with his or her corresponding phone number. Use the algorithms
that deal with ranges (**lower_bound**, **upper_bound**, **equal_range**,
etc.). Sort with the last name acting as a primary key and the first name
acting as a secondary key. Assume that you will read the names and numbers from
a file where the format will be as follows. (Be sure to order them so that the
last names are ordered, and the first names are ordered within the last
names.):

** **

John Doe 345 9483

Nick Bonham 349 2930

Jane Doe 283 2819

34. Given a file with data similar to the following, pull all the
state acronyms from the file and put them in a separate file. (Note that you
can t depend on the line number for the type of data. The data is on random
lines.)

ALABAMA

AL

AK

ALASKA

ARIZONA

AZ

ARKANSAS

AR

CA

CALIFORNIA

CO

COLORADO

etc.

When complete, you should have a file with all the state acronyms which
are:

AL AK AZ AR CA CO CT DE FL GA HI ID IL IN IA KS KY LA ME MD MA MI MN MS MO
MT NE NV NH NJ NM NY NC ND OH OK OR PA RI SC SD TN TX UT VT VA WA WV WI WY

35. Make an **Employee **class with two data members: **hours **and
**hourlyPay**. Employee shall also have a **calcSalary( )** function
which returns the pay for that employee. Generate random hourly pay and hours
for an arbitrary amount of employees. Keep a **vector<Employee*>**.
Find out how much money the company is going to spend for this pay period.

36. Race **sort( )**,** partial_sort( )**,** **and
**nth_element( )** against each other and find out if it s really worth
the time saved to use one of the weaker sorts if they re all that s needed.