程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> C++之Effective STL學習筆記Item20

C++之Effective STL學習筆記Item20

編輯:C++入門知識

 Q:假設我們現在需要一個string*的set,我們向其插入一些動物到這個set中:

<*> ssp;                                                               
ssp.insert( ( ( ( ());

You then write the following code to print the contents of the set, expecting the strings to come out in alphabetical order. After all, sets keep their contents sorted.

<< i << endl;

真正打印出來的會是字符串的指針值。或許你說那我在i前面加個*,取出字符串不就搞定了,so easy!是可以,但是別忘了我們的需求,我們需要使得字符串有序排列,而這樣得到的只是對指針值有序排列了,顯然不滿足我們得要求!

其實我們上述的語句set<string*> ssp;是下面語句的簡化寫法:

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

If you want the string* pointers to be stored in the set in an order determined by the string values, you can’t use the default comparison functor class less<string*>. You must instead write your own comparison functor class, one whose objects take string* pointers and order them by the values of the strings they point to. Like this:

 binary_function< *,  *, > ()(  *ps1,   *ps2)  *ps1 < *

 Then you can use StringPtrLess as ssp’s comparison type:

typedef <*, StringPtrLess>

好了,最終的解決方案出爐了:

typedef <*, StringPtrLess> ( ( ( (<< *i <<

當然,其中的打印過程可以有很多花樣,比如我也可以利用alogrithm來完成,也是OK的。

If you want to use an algorithm instead, you could write a function that knows how to dereference string* pointers before printing them, then use that function in conjunction with for_each:

 print(  *<< *ps <<

 感謝大家的閱讀,希望能幫到大家!

 Published by Windows Live Writer.

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved