开发者

defining < operator for map of list iterators

开发者 https://www.devze.com 2022-12-25 02:54 出处:网络
I\'d like to use iterators from an STL list as keys in a map.For example: using namespace std; 开发者_如何学编程

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;
0

精彩评论

暂无评论...
验证码 换一张
取 消