理解std :: search谓词

时间:2017-09-19 17:54:15

标签: c++ c++11

我正在尝试理解我从here读到的td::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。现在从我观察到的是针头的第一个字母将与干草堆的所有字母进行比较 - 因此W将与H然后E然后L进行比较....所以

1 个答案:

答案 0 :(得分:1)

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

我在这里附上了一些官方文档的链接。

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

E.g。 因此将“Hello”与“ell”进行比较将是

"H" to "e" -> false
"e" to "e" -> true continue
"l" to "l" -> true continue
"l" to "l" -> true return
相关问题