【问题标题】:Understanding the std::search predicate理解 std::search 谓词
【发布时间】:2018-02-28 14:56:01
【问题描述】:

我试图理解我从here 读到的 std::search 谓词。为了方便起见,我把它贴在下面。

#include <algorithm>
#include <string>
#include <cctype>

// haystack=Hello and needle=World
/// Try to find in the Haystack the Needle - ignore case
bool findStringIC(const std::string & strHaystack, const std::string & strNeedle)
{
  auto it = std::search(
    strHaystack.begin(), strHaystack.end(),
    strNeedle.begin(),   strNeedle.end(),
    [](char ch1, char ch2) { 

      std::cout << ch1 << "?" << ch2 << "\n";
    return std::toupper(ch1) == std::toupper(ch2); 
   }
  );
  return (it != strHaystack.end() );
}

基本上我对它(谓词)的工作方式感到困惑。假设干草堆是单词Hello,而针是单词World。现在从我所观察到的,针的第一个字母将与 haystack 的所有字母进行比较 - 所以 W 将与 H 然后 E 然后 L 进行比较......所以

【问题讨论】:

  • 25 次比较有什么疯狂的实现?
  • 我对这个谓词如何工作的理解有误吗?
  • 不,std::search 不是这样工作的。
  • 谓词与std::searchwhich 比较完全无关。谓词影响的是如何比较发生。
  • @SamVarshavchik 你能解释一下吗?或链接

标签: c++ c++11


【解决方案1】:

http://www.cplusplus.com/reference/algorithm/search/?kw=search

我在这里提供了一些官方文档的链接。

预测将返回第二个对象的第一次出现。

例如 因此,将“Hello”与“ell”进行比较是

"H" to "e" -> false
"e" to "e" -> true continue
"l" to "l" -> true continue
"l" to "l" -> true return

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-29
    • 1970-01-01
    • 1970-01-01
    • 2017-03-01
    • 1970-01-01
    • 2021-08-26
    相关资源
    最近更新 更多