Take some time to browse the online STL documentation graciously provided by SGI (10 years ago!). This guide will be your very good friend this term. You should especially become familiar with the Table of Contents, which lets you find documentation of concepts and implementations very quickly, and the Index, which lets you track down any odds and ends you might need for your programs.
The Standard Template Library provides a great set of efficient, generic, modular tools for writing programs. Try the following warm-up exercises in STL. Save each of the following code snippets in a file named exercisen.cc, where n is the exercise number.
Create a vector of 100 ints. Fill it with 100 small, random integers between 1 and 100, inclusive, by using the appropriate mutating algorithm. Generate these numbers by passing the mutating algorithm a function object (or perhaps a simple function) that models a Generator. (Your function object should use rand() and the modulo operator, at least.)
Since it would be nice to verify your code is working, use the copy algorithm to write your vector to cout via an ostream_iterator parameterized on ints.
Create a new vector to hold 100 strings. Use another Generator that you write to fill it with 100 random alphabetic strings of random lengths between 5 and 15 characters inclusive.
Sort the vector you've made using the version of sort that applies operator< to the vector. Display this sorted vector in a similar fashion to the way you displayed exercise 1's result.
Then, re-sort the vector by length of string (ascending). You'll want to use a comparator that conforms to the Strict Weak Ordering model. Output your re-sorted vector to stdout.
Generate a vector of 100 random integers between 1 and 100, as before, then write some code to count how many of these numbers are odd and how many are even, in a single pass over the integers. Do this by creating a simple function object that implements the unary_function model, and that maintains some internal state. You should then be able to apply it with the for_each algorithm and then extract the counts at the end.
Have a look at this code:
vector<int> v;
v.push_back(1);
v.push_back(4);
v.push_back(2);
v.push_back(8);
v.push_back(5);
v.push_back(7);
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
cout << endl;
vector<int>::iterator new_end =
remove_if(v.begin(), v.end(),
compose1(bind2nd(equal_to<int>(), 0),
bind2nd(modulus<int>(), 2)));
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
cout << endl;
(The compose1 function can be difficult to track down in the
g++ compiler. It should be in the __gnu_cxx namespace,
and you will need to #include <ext/functional> to get the
definition.)
Paste it into exercise4.cc, and use a comment block at the top to explain:
Of course, actually fix the code, compile, and verify that it works the way it was probably meant to work.
Use the STL docs to help you understand what bind2nd and compose1 do.