[   ^ to index...   |   <-- previous   ]

A few sample STL algorithms

The two algorithms on this page are simple; essentially, they save us the trouble of writing common loops. However, they also allow us to code at a more abstract, expressive level. Of course, not all STL algorithms are this trivial. (Sample code...)

find()

template <class In, class T> In find(In first, In last, const T& val);

The find template searches for a value in a container:

vector<int> vec; vec.push_back(6); vec.push_back(9); vec.push_back(9); vector<int>::iterator find6 = find(vec.begin(), vec.end(), 6); if (find6 != vec.end()) // if element is found... cout << *find6 << endl; // will print "6"

count()

count() simply counts the number of items matching a given value. (Actually, count() does not return int, but the real return type is complicated.) Continuing the code sample above, its usage is as follows:

int count9 = count(vec.begin(), vec.end(), 9); cout << count9 << endl; // should print "2"

Incidentally, here's how count() is implemented:

template <class In, class T> int count(In first, In last, const T& val) { int res = 0; while (first != last) if (*first++ == val) ++res; return res; }

Conclusion

To achieve its goals (reusability and performance), the STL pervasively uses advanced C++ features. Therefore, you should expect that it will take you a long time to grow fluent in the STL.

Don't feel that you have to use the STL in all your code; nor should you attempt to use the entire framework at first. Initially, you will probably be attracted by the container classes only. Over time, you may start using iterators instead of container member functions to access elements, and when you get comfortable you may integrate the STL algorithms.


Last modified: Wed Aug 16 20:15:18 PDT 2000