-1

I am trying to understand the std::search predicate which I read about from here. I have posted it below for convenience.

#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() );
}

Essentially I am confused by how it(the predicate) works. Suppose the haystack is the word Hello and the needle is the word World. Now from what I have observed is that the first letter of needle will get compared to all the letters of haystack - so W will get compared to H then E then L.... so

MistyD
  • 16,373
  • 40
  • 138
  • 240

1 Answers1

1

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

I included a link to some official documentation here.

The predict would return the first occurrence of the second object.

E.g. So comparing "Hello" to "ell" would be

"H" to "e" -> false
"e" to "e" -> true continue
"l" to "l" -> true continue
"l" to "l" -> true return
James Maa
  • 1,764
  • 10
  • 20