开发者

C++ -- why don't apply ptr_fun on ciCharLess when calling lexicographical_compare

Question 1>

I would like to know why in case I we have to use not2(ptr_fun(ciCharCompare)), while in case II, we just need to use ciCharLess. Why not use ptr_fun(ciCharLess) instead?

Question 2>

Is there a general rule that I can follow when to use which form?

Thank you

case I:

开发者_JAVA百科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 );

pred:

Binary predicate taking two elements as argument

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/

comp:

Comparison function object that, taking two values of the same type than those contained in the range, returns true if the first argument is to be considered less than the second argument.


Why not use ptr_fun(ciCharLess) instead?

You could use ptr_fun(ciCharLess) if you wanted. All ptr_fun does is convert your function pointer into a functor, which contains some typedefs such as result_type. Most algorithms don't need it, but some (particularly binders such as not2) do need it.

Generally speaking, because you're never going to be wrong by using ptr_fun on a function pointer type (note: applying it to a type which is already a functor is wrong), I just use it everywhere. The worst thing that can happen then is someone raising their eyebrows a bit as to why the wrapper is there if it need not be. If you don't use it and it needs it the compiler is going to complain quite loudly at you.

For more information on the specific bits that ptr_fun is for, see Scott Meyers' Effective STL Item 41: Understand the reasons for ptr_fun, mem_fun, and mem_fun_ref.

(Long story short, these binder adapters are required to make up for some syntactic inconsistencies in the language; e.g. functors and function pointers are called like identifier(args), member functions called via a pointer are object->identifier(args), and member functions called via a reference are object.identifier(args).)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜