defining < operator for map of list iterators
I'd like to use iterators from an STL list as keys in a map. For example:
using namespace std;
开发者_如何学编程
list<int> l
;map<list<int>::const_iterator, int> t;
int main(int argv, char * argc) {
l.push_back(1); t[l.begin()] = 5; }
However, list iterators do not have a comparison operator defined (in contrast to random access iterators), so compiling the above code results in an error:
/usr/include/c++/4.2.1/bits/stl_function.h:227: error: no match for ‘operator<’ in ‘__x < __y’
If the list is changed to a vector, a map of vector const_iterators compiles fine.
What is the correct way to define the operator < for list::const_iterator?
Parameterise map
with a custom comparator:
struct dereference_compare {
template <class I>
bool operator()(const I& a, const I& b) {
return *a < *b;
}
};
map<list<int>::const_iterator, int, dereference_compare> t;
精彩评论