-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
  • 13,289
  • 28
  • 108
  • 198
  • What crazy implementation does 25 comparisons with that? – T.C. Sep 19 '17 at 17:58
  • is my understanding wrong of how this predicate is working ? – MistyD Sep 19 '17 at 17:59
  • 2
    No, that's not how `std::search` works. – Sam Varshavchik Sep 19 '17 at 17:59
  • 1
    The predicate has absolutely nothing to do, whatsoever, with ***which*** comparisons `std::search` makes. What the predicate affects is ***how*** the comparison takes place. – Sam Varshavchik Sep 19 '17 at 18:00
  • @SamVarshavchik could you explain that please ? or a link – MistyD Sep 19 '17 at 18:01
  • The "[Possible Implementation (Second version)](https://en.cppreference.com/w/cpp/algorithm/search#Possible_implementation)" section on cppreference might help clear things up for you. – 0x5453 Sep 19 '17 at 18:01
  • "from what I have observed". On what implementation did you observe that comparison behavior with 25 comparisons? – T.C. Sep 19 '17 at 18:02
  • I cant understand why this would make more than 1 comparison, after `W` != `H` the needle surely cannot be found? – Nick Sep 19 '17 at 18:06
  • So where is the "O will be compared HELLO letters consecutively"? – T.C. Sep 19 '17 at 18:13
  • @NickA How so? What if your haystack is "WHello"? – 0x5453 Sep 19 '17 at 18:17
  • @0x5453 I mean in this exact example – Nick Sep 19 '17 at 18:18
  • @NickA. Sure. But my point is that `std::search` doesn't necessarily know that it can stop after the first letter, because it hasn't checked the rest of the haystack yet. (Unless it does some extra checks like comparing string sizes.) – 0x5453 Sep 19 '17 at 18:20

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,532
  • 7
  • 19