2011-05-03 58 views
1

問題1>C++ - 爲什麼叫lexicographical_compare時並不適用於ciCharLess ptr_fun

我想知道爲什麼在我的情況下,我們必須使用NOT2(ptr_fun(ciCharCompare)),而在情況二,我們只需要使用ciCharLess。爲什麼不使用ptr_fun(cICharLess)取而代之?

問2>

有沒有辦法,我可以按照時使用的形式的一般規則?

謝謝

case I: 

int ciCharCompare(char c1, char c2) 
{ 
// case-insensitively compare chars c1 and c2 
// return -1 if c1 < c2 
// return 0 if c1 == c2 
// return 1 if c1 > c2 
} 

string s1("Test 1"); 
string s2("test 2222222222222222"); 

pair<string::const_iterator, string::const_iterator> 
    p = mismatch(s1.begin(), s1.end(), 
       s2.begin(), 
       not2(ptr_fun(ciCharCompare)))); 

http://www.cplusplus.com/reference/algorithm/mismatch/

template <class InputIterator1, class InputIterator2, class BinaryPredicate> 
pair<InputIterator1, InputIterator2> 
mismatch (InputIterator1 first1, InputIterator1 last1, 
      InputIterator2 first2, BinaryPredicate pred); 

預計值
二元謂詞取兩個元素作爲參數

Case II:  
bool ciCharLess(char c1, char c2) 
{ 
    // return true if c1 precedes c2 in a case insensitive comparison 
} 

lexicographical_compare(s1.begin(), s1.end(), s2.begin(), s2.end(), 
         ciCharLess); 

http://www.cplusplus.com/reference/algorithm/lexicographical_compare/

排版
比較函數對象,服用相同類型的比包含在所述範圍內的兩個值中,如果第一個參數將被認爲是小於第二個參數返回true。

回答

2

爲什麼不使用ptr_fun(ciCharLess)呢?

如果您願意,您可以使用ptr_fun(ciCharLess)。所有ptr_fun都會將您的函數指針轉換爲函子,其中包含一些類型定義,如result_type。大多數算法不需要它,但是一些(特別是粘合劑,如not2)確實需要它。

一般來說,因爲你永遠不會成爲錯誤通過一個函數指針類型使用ptr_fun(注:它應用到一個類型它已經是一個仿函數錯誤的),我只是用它無處不在。可能發生的最糟糕的事情是,有人會提起他們的眉毛,以便爲什麼包裝物在那裏,如果不需要的話。如果你不使用它並且需要它,編譯器會非常大聲地抱怨你。

有關特定比特ptr_fun是更多的信息,請參閱Scott Meyers' Effective STL項目41:理解爲ptr_funmem_funmem_fun_ref的原因。

(長話短說,需要這些粘合劑適配器來彌補語言中的一些語法不一致;如仿函數和函數指針被稱爲像identifier(args),通過指針叫做成員函數object->identifier(args),並且通過所謂的成員函數參考文獻object.identifier(args)。)

相關問題