I want to employ iterator of a list container as the key field of a map container. I used to believe the map will compare iterators by the precedence of the two elements pointed by the iterator automatically. But the compiler complained that there is no operator<. Then, how can I implement the comparator for the map properly to accept iterator of every list element only once.
I am sorry for not explaining my problem clearly. For the map requires a less comparator, I have to explicitly define the precedence of the list iterator. How to compare two list iterators by the sequence of the elements they point to, in other words, how can I know the element pointed by list<XXX>::iterator A is located before the element pointed by list<XXX>::iterator B? Thanks for any hints.
Are you talking about an std::list::iterator? If you are, then you can't.
Iterators do not keep track of their position in the chain. The reason for this is because it's very easy for their position to change. Every time an item is added to or removed from the list, the entire list would need to be traversed and all the position markers updated. This would add a lot of overhead for something rather trivial.
Because of this there's no < operator and no way to compare 2 iterators.
There's a work-around if you're dealing with a random access container type like vector or deque, but it would take some finnagling to get it to work with map like this.
Basically: you're hosed. You'll have to rethink this design. This is a rather strange way to use iterators anyway.
I think OP wants to compare the values referenced by the iterators, not by the iterators
themselves, in which case a simple compare function is needed.
1 2 3
template< typename Iter >
bool iter_less_than( Iter first, Iter second )
{ return *first < *second; }
though I have to agree with Disch... this seems weird. If the goal ultimately is to be
able to sort a container by more than one index, then consider using a boost::multi_index_container instead.