2

C++ STL includes (http://www.cplusplus.com/reference/algorithm/includes/) Test whether sorted range includes another sorted range Returns true if the sorted range [first1,last1) contains all the elements in the sorted range [first2,last2)

void Test_STL_Includes() {
    vector<char>secondRowInKeyboard{ 'a','A','s','S','d','D','f','F','g','G','h','H','j','J','k','K','l','L' };

    sort(secondRowInKeyboard.begin(), secondRowInKeyboard.end());

    string s("Alaska");
    sort(s.begin(), s.end());

    if (includes(secondRowInKeyboard.begin(), secondRowInKeyboard.end(), s.begin(), s.end()))
    {
        cout << "Matches";
    }
    else
    {
        cout << "Not Matches";
    }

}

Expected: "Matches"

Actual: "Not Matches"

Am I making some mistake?

M.M
  • 138,810
  • 21
  • 208
  • 365
Vikrant
  • 1,149
  • 12
  • 19

3 Answers3

3

It doesn't match because the "needle" contains two a but the "haystack" only has one a.

See also: What does std::includes actually do? ; another way to state it is that the set intersection must equal the second set.

M.M
  • 138,810
  • 21
  • 208
  • 365
1

Based on this two pointer implementation from cplusplus.com:

template <class InputIterator1, class InputIterator2>
  bool includes (InputIterator1 first1, InputIterator1 last1,
                 InputIterator2 first2, InputIterator2 last2)
{
  while (first2!=last2) {
    if ( (first1==last1) || (*first2<*first1) ) return false;
    if (!(*first1<*first2)) ++first2;
    ++first1;
  }
  return true;
}

The first pointer is pushed when one character is matched. Therefore you need two a characters since there's two of them in Alaska.

An extra a in the vector gets you the desired result:

vector<char>secondRowInKeyboard{'a','a','A','s','S','d','D','f','F','g','G','h','H','j','J','k','K','l','L' };
1

Thanks for your answers. It helped me understood my mistake.

I solved this issue by converting Alaska into a set.

void Test_STL_Includes() {
    vector<char>secondRowInKeyboard{ 'a','A','s','S','d','D','f','F','g','G','h','H','j','J','k','K','l','L' };

    sort(secondRowInKeyboard.begin(), secondRowInKeyboard.end());

    string s("Alaska");
    set<char> temp(s.begin(), s.end());

    if (includes(secondRowInKeyboard.begin(), secondRowInKeyboard.end(), temp.begin(), temp.end()))
    {
        cout << "Matches";
    }
    else
    {
        cout << "Not Matches";
    }

}
Vikrant
  • 1,149
  • 12
  • 19