Standard Template Library |
As we have discussed the standard template library includes classes for vector, stack, queue, priority_queue, deque, and list, where list is a linked list. It also includes classes for such concepts as set, map, multiset, etc. that we will discuss later.
Use of most of these container classes is pretty straightforward, though you need to read the documentation. Here I'd like to focus on issues involving ordered containers and how we could provide orderings to be used by the template, something we did in Java using Comparator class.
Let's go back and look at a relatively simple problem of finding the max element of a collection.
#include <iostream> #include <vector> using namespace std; template <typename T, typename Comparator> const T & findMax(const vector<T> & a, Comparator cmp) { int maxIndex = 0; for (int i = 1; i < a.size(); i++) { if (cmp.isLessThan( a[maxIndex], a[i] )) { maxIndex = i; } } return a[maxIndex]; } class LessThanByLength { public: bool isLessThan( const string & lhs, const string & rhs) const { return lhs.size() < rhs.size(); } }; int main() { vector<string> a; a.push_back("abc"); a.push_back("aceg"); a.push_back("xz"); cout << findMax(a, LessThanByLength() ) << endl; return 0; }
Notice that have implicit requirement that Comparator support "isLessThan" method. No checking at compile time, but checked when instantiate. In this case, works without difficulty because LessThanByLength supports such a member.
Using operator overloading, we can simplify findMax to that we don't have to refer to the class LessThanByLength. The idea is that we will instead just be able to write isLessThan.
#include <iostream> #include <vector> using namespace std; template <typename T, typename Comparator> const T & findMax(const vector<T> & a, Comparator isLessThan) { int maxIndex = 0; for (int i = 1; i < a.size(); i++) { if (isLessThan( a[maxIndex], a[i] )) { maxIndex = i; } } return a[maxIndex]; } class LessThanByLength { public: bool operator() ( const string & lhs, const string & rhs) const { return lhs.size() < rhs.size(); } }; int main() { vector<string> a; a.push_back("abc"); a.push_back("aceg"); a.push_back("xz"); cout << findMax(a, LessThanByLength() ) << endl; return 0; }
Notice that isLessThan(a,b) abbreviates isLessThan.operator()(a,b), which is like the cmp.isLessThan(a,b) from the first version above.
We'll see next time how to use this to use comparators in STL classes.
Standard Template Library |