Algorithms
The STL also provides some standard algorithms. There are way to many to list here, but they all work pretty much the same way. I have selected some random ones:
- unsigned count(InIter first, InIter last, T value)
counts all elements in the range [first, last[ that match the given value.
- FwdIter max_element(FwdIter first, FwdIter last)
returns an iterator that points to the larges element in the range [first,last[. (can you guess what min_element does?)
- InIter find(InIter first, InIter last, T value)
returns an iterator to the first occurence of value in the range [first,last[.
- void sort(RandIter first, RandIter last)
sorts the elements in [first,last[ to be ascending. The value type of the container must support the operator<
- void random_shuffle(RandIter first, RandIter last)
randomly shuffles the elements in the range [first,last[.
count and find require an Input Iterator or better, maxElement requires a forward iterator or better, sort and random_shuffle require a random access iterator.
There are about 66 algorithm in the STL. For a complete reference, read Pg. 270-274 and Pg 328-369.
To use algorithms, you have to include the <algorithm>
I want you to know the five algorithms given here, If you need to know other ones then I'll provide the reference.
Example:
list<int> l; l.push_back(1); l.push_back(2); l.push_back(1); l.push_back(3); // There are two 1's in there, so this will print 2 cout << count(l.begin(),l.end(),1) << endl;
Practice: Print out the value of the largest element in l.
cout << *(max_element(l.begin(),l.end()));
Here is another example:
vector<int> v; for (int i=1;i<100;i++) v.push_back(i); random_shuffle(v.begin(),v.end()); cout << "The largest element is now at "; cout << max_element(v.begin(),v.end())-v.begin() << endl;