どのクラスがmapのキー値として使用できるか
C++のmapを学ぶ時、1段のコードを書きました
このコードはコンパイル中にエラーが発生しました「/usr/include/c+/4.6/bits/stl_function.h:236:22:エラー:'operator<'は'_x<_y'で一致していません」が、不思議なことに、
もし私がmaaをinsert(make_pair(a1,a2));make_に変更pair(a1,a2);その後はスムーズにコンパイルできます.この様子ではmapのinsertメソッドを呼び出すときにコンパイルが間違っていますが、なぜですか?
ネット上で狂ったように検索した後、ブログ(http://blog.csdn.net/xie376450483/article/details/6329408)エラーの原因を回答しました.このブログには2つの点が記載されています.
1.「map内部記憶メカニズムは、実際には赤と黒のツリーをベースとしており、赤と黒のツリーはノードを挿入する際に、大きさの対比に従って適切な位置で挿入動作を実行しなければならない.したがって、キーワードとしては、少なくとも「<」という比較オペレータが必要である.
2.STLにおけるlessシミュレーション関数の定義は
lessがこの比較子を呼び出すと、const方式で転送され、非const方式で呼び出すことはできない.したがって、定義メンバ関数bool operator<(const struct st&rs)を用いることができず、関数内部で定義された比較オペレータの代わりに、友連関数[friend bool operator<(const A&a,const A&b)]を用いなければならない.
クラスAにoperator<メソッドを追加
その後、再コンパイルが通過する.
実はSTLの中のmapの定義からも明らかで、mapの定義は以下の通りです.
比較述語があり、デフォルトでは「<」
- #include <iostream>
- #include <map>
- using namespace std;
-
- class A
- {
- public:
- A(){cout<<"A created"<<endl;}
- A(const A& a){cout<<"A created by another a"<<endl;}
- ~A(){cout<<"A destoried"<<endl;}
- friend ostream & operator << (ostream& os,const A& a)
- {
- os<<"print a"<<endl;
- return os;
- }
- };
- int main(int argc, const char *argv[])
- {
-
- A a1;
- A a2(a1);
- map<A,A> maa;
- //make_pair(a1,a2);
- maa.insert(make_pair(a1,a2));
- return 0;
- }
このコードはコンパイル中にエラーが発生しました「/usr/include/c+/4.6/bits/stl_function.h:236:22:エラー:'operator<'は'_x<_y'で一致していません」が、不思議なことに、
もし私がmaaをinsert(make_pair(a1,a2));make_に変更pair(a1,a2);その後はスムーズにコンパイルできます.この様子ではmapのinsertメソッドを呼び出すときにコンパイルが間違っていますが、なぜですか?
ネット上で狂ったように検索した後、ブログ(http://blog.csdn.net/xie376450483/article/details/6329408)エラーの原因を回答しました.このブログには2つの点が記載されています.
1.「map内部記憶メカニズムは、実際には赤と黒のツリーをベースとしており、赤と黒のツリーはノードを挿入する際に、大きさの対比に従って適切な位置で挿入動作を実行しなければならない.したがって、キーワードとしては、少なくとも「<」という比較オペレータが必要である.
2.STLにおけるlessシミュレーション関数の定義は
- template <class _Tp>
- struct less : public binary_function<_Tp,_Tp,bool>
-
- {
- bool operator()(const _Tp& __x, const _Tp& __y) const { return __x < __y; }
- };
lessがこの比較子を呼び出すと、const方式で転送され、非const方式で呼び出すことはできない.したがって、定義メンバ関数bool operator<(const struct st&rs)を用いることができず、関数内部で定義された比較オペレータの代わりに、友連関数[friend bool operator<(const A&a,const A&b)]を用いなければならない.
クラスAにoperator<メソッドを追加
- friend bool operator < (const A& a,const A& b)
- {
- return true;
- }
その後、再コンパイルが通過する.
実はSTLの中のmapの定義からも明らかで、mapの定義は以下の通りです.
- template <
- class Key,
- class Type,
- class Traits = less<Key>,
- class Allocator=allocator<pair <const Key, Type> >
- >
- class map
比較述語があり、デフォルトでは「<」