简体   繁体   中英

<operator missing when iterating through c++ map

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)

在迭代器比较中使用!=代替<。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM