简体   繁体   English

<operator missing when iterating through c++ map

[英]<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. operator <仅适用于随机访问迭代器。 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). 由于std :: maps通常是使用某种平衡树来实现的,因此通常没有快速的方法来找出一个迭代器是否指向另一个元素之前的元素(尽管结尾是一个例外)。

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. 我想这背后的原因是,这些神秘的编译器错误迫使您重新考虑代码,并自己实现operator <如果发现这是解决问题的最佳方法,请自己执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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