どのクラスがmapのキー値として使用できるか

6426 ワード

C++のmapを学ぶ時、1段のコードを書きました
 

      
      
      
      
  1. #include <iostream> 
  2. #include <map> 
  3. using namespace std; 
  4.  
  5. class A 
  6.     public
  7.     A(){cout<<"A created"<<endl;} 
  8.     A(const A& a){cout<<"A created by another a"<<endl;} 
  9.     ~A(){cout<<"A destoried"<<endl;} 
  10.     friend ostream & operator << (ostream& os,const A& a) 
  11.     { 
  12.         os<<"print a"<<endl; 
  13.         return os; 
  14.     } 
  15. }; 
  16. int main(int argc, const char *argv[]) 
  17.  
  18.     A a1; 
  19.     A a2(a1); 
  20.     map<A,A> maa; 
  21.     //make_pair(a1,a2); 
  22.     maa.insert(make_pair(a1,a2)); 
  23.     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シミュレーション関数の定義は

  
  
  
  
  1. template <class _Tp> 
  2. struct less : public binary_function<_Tp,_Tp,bool
  3.  
  4.       bool operator()(const _Tp& __x, const _Tp& __y) const { return __x < __y; } 
  5. }; 

lessがこの比較子を呼び出すと、const方式で転送され、非const方式で呼び出すことはできない.したがって、定義メンバ関数bool operator<(const struct st&rs)を用いることができず、関数内部で定義された比較オペレータの代わりに、友連関数[friend bool operator<(const A&a,const A&b)]を用いなければならない.
クラスAにoperator<メソッドを追加

  
  
  
  
  1. friend bool operator < (const A& a,const A& b) 
  2.     return true

その後、再コンパイルが通過する.
実はSTLの中のmapの定義からも明らかで、mapの定義は以下の通りです.
 

  
  
  
  
  1. template < 
  2.    class Key, 
  3.    class Type, 
  4.    class Traits = less<Key>, 
  5.       class Allocator=allocator<pair <const Key, Type> > 
  6. class map 

比較述語があり、デフォルトでは「<」