gpt4 book ai didi

C++——为什么在调用 lexicographical_compare 时不在 ciCharLess 上应用 ptr_fun

转载 作者:行者123 更新时间:2023-11-30 04:34:36 26 4
gpt4 key购买 nike

问题一>

我想知道为什么在情况 I 中我们必须使用 not2(ptr_fun(ciCharCompare)),而在情况 II 中,我们只需要使用 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。

最佳答案

Why not use ptr_fun(ciCharLess) instead?

如果你愿意,你可以使用ptr_fun(ciCharLess)ptr_fun 所做的就是将您的函数指针转换为一个仿函数,其中包含一些类型定义,例如result_type。大多数算法不需要它,但某些算法(特别是绑定(bind)器,例如 not2)确实需要它。

一般来说,因为在函数指针类型上使用 ptr_fun 永远不会错误(注意:将它应用于已经是仿函数的类型错了),我到处都用它。那时可能发生的最糟糕的事情是有人对为什么 wrapper 在不需要的情况下会在那里感到有点惊讶。如果您不使用它而它需要它,编译器会大声提示您。

有关 ptr_fun 的特定位的更多信息,请参阅 Scott Meyers' Effective STL第 41 条:了解 ptr_funmem_funmem_fun_ref 的原因。

(长话短说,需要这些 Binder 适配器来弥补语言中的一些句法不一致;例如仿函数和函数指针被调用为 identifier(args),通过指针调用成员函数是object->identifier(args),通过引用调用的成员函数是object.identifier(args)。)

关于C++——为什么在调用 lexicographical_compare 时不在 ciCharLess 上应用 ptr_fun,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5864669/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com