tags:

views:

244

answers:

2

The following code does not want to compile. See the included error message.

Code:

#include <map>
#include <vector>
#include <iostream>

class MapHolder {
public:
    std::map<std::vector<std::string>,MapHolder> m_map;

    void walk_through_map() {
     std::map<std::vector<std::string>,MapHolder>::iterator it;
     for(it = m_map.begin(); it < m_map.end(); ++it) {
      it->second.print();
     }
    }

    void print() { std::cout << "hey" << std::endl; }
};

int
main(int argc, char *argv[])
{
    MapHolder m;
    m.walk_through_map();
}

Error:

$ g++ test.cc -O test
test.cc: In member function 'void MapHolder::walk_through_map()':
test.cc:12: error: no match for 'operator<' in 'it < ((MapHolder*)this)->MapHolder::m_map.std::map<_Key, _Tp, _Compare, _Alloc>::end [with _Key = std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >, _Tp = MapHolder, _Compare = std::less<std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, _Alloc = std::allocator<std::pair<const std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >, MapHolder> >]()'

I used this type of map and iterating process multiple times before. What's the problem here? How can it be solved.

(The code looks meaningless, but this is a reduced sample which is still supposed to work)

+6  A: 

Use != instead of < in iterator comparison.

Gábor Hargitai
I am emberassed, it's so right! Thanks!
Peter Smit
+1  A: 

operator< is only available for random access iterators. Since std::maps are usually implemented using some sort of balanced tree, there is usually no fast way to find out whether one iterator points to an element before another one (though end is an exception).

I guess the reasoning behind this is that these mysterious compiler errors force you to think about your code again and implement operator< yourself if you find that this is the best way to solve your problem.

Tobias