1. 程式人生 > >Effective_STL 學習筆記(二十) 為指標的關聯容器指定比較型別

Effective_STL 學習筆記(二十) 為指標的關聯容器指定比較型別

 

對於 string* 指標的 set,列印 set <string*> ssp 內容:

1  for( set<string*>::const_iterator i = ssp.begin(); i != ssp.end(); i++ )
2     cout<< *i <<endl;
1  copy( ssp.begin(), ssp.end(), ostream_iterator<string>(cout, "\n") );
                          // 把ssp中的字串拷貝到 cout 內

前一種迴圈的方式 *i 是指標。即使用 **i 替代,set 建立時按指標排序

copy的方式,編譯器檢測到迭代器傳遞的 string* 與ostream_iterator 需要列印物件不匹配。

 

string*  的 set 的建立:

1   set< string*, less<string*>, allocator<string*> >  ssp;

如果想要 string* 指標以字串值確定順序被儲存在 set 中,不能使用預設比較仿函式類 less<string*>,必須改為自己的比較仿函式類

,它的物件帶有 string* 指標並按照指向的字串值來進行排序:

1   struct StringPtrLess: public binary_function< const string*, const string*, bool >
2   {
3     bool operator()( const string *ps1, const string *ps2 ) const
4     {
5       return *ps1 < *ps2;
6     }
7   };

使用 StringPtrLess 作為 ssp 的比較型別:

1   typedef set
< string*, StringPterLess > StringPtrSet; 2   StringPtrSet ssp;    // 建立StringPtrSet 定義的順序排序 3   . . .

列印兩種方式: **i 或者使用演算法

1   for( StringPtrSet::const_iterator i = ssp.begin(); i != ssp.end(); i++ )
2     cout<< **i <<endl;
1   void print( const string* ps )
2   {
3     cout<< *ps<<endl;
4   }
5 
6   for_each( ssp.begin(), ssp.end(), print );

注意到使用的 “比較型別”,是仿函式類我不是一個真正的函式,因為 set 的模板三個引數都是一種型別

用於比較的模仿函式模板:

1   struct DereferenceLess
2   {
3     template< typename PtrType >
4     bool operator()( PtrType pT1, PtrType pT2 ) const
5     {
6       return *pT1 < *pT2;
7     }
8   };
1   set< string*, DereferenceLess > ssp;

 

本條款是關於指標的關聯容器,但它也可以應用於表現為指標的物件的容器,例如,智慧指標和迭代器