質問

次のコードはコンパイルしません。付属のエラーメッセージを参照してください。

コード:

#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();
}

エラー:

$ 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> >]()'

以前、このタイプのマップと反復プロセスを複数回使用しました。ここで問題は何ですか?どうすれば解決できます。

(コードは無意味に見えますが、これはまだ動作するはずの縮小サンプルです)

役に立ちましたか?

解決

&lt;の代わりに!=を使用します反復子の比較。

他のヒント

演算子&lt;ランダムアクセスイテレータでのみ使用可能です。 std :: mapsは通常、何らかのバランスの取れたツリーを使用して実装されるため、通常、あるイテレータが別のイテレータの前にある要素を指しているかどうかをすばやく確認する方法はありません(ただし、終了は例外です)。

この背後にある理由は、これらの不可解なコンパイラエラーにより、コードについて再度考え、operator&lt;これがあなたの問題を解決する最良の方法であることがわかった場合、あなた自身。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top