- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
问题一>
我想知道为什么在情况 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_fun
、mem_fun
和 mem_fun_ref
的原因。
(长话短说,需要这些 Binder 适配器来弥补语言中的一些句法不一致;例如仿函数和函数指针被调用为 identifier(args)
,通过指针调用成员函数是object->identifier(args)
,通过引用调用的成员函数是object.identifier(args)
。)
关于C++——为什么在调用 lexicographical_compare 时不在 ciCharLess 上应用 ptr_fun,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5864669/
我想使用 c++ 算法库中的函数 lexicographical_compare。 但就using语句而言,我不知道该写什么。例如 using std::lexicographical_compare
有没有什么方法可以使用 C++ 中的 lexicographical_compare() 函数对字符串进行排序? 我可以通过 STL 排序来完成,但我的问题是关于 lexicographical_co
问题一> 我想知道为什么在情况 I 中我们必须使用 not2(ptr_fun(ciCharCompare)),而在情况 II 中,我们只需要使用 ciCharLess。为什么不改用 ptr_fun(c
我是一名优秀的程序员,十分优秀!