【问题标题】:Is it bug in std::includes or am I doing something wrong是 std::includes 中的错误还是我做错了什么
【发布时间】:2019-07-04 11:43:57
【问题描述】:

C++ STL includes (http://www.cplusplus.com/reference/algorithm/includes/) 测试排序范围是否包含另一个排序范围 如果排序范围 [first1,last1) 包含排序范围 [first2,last2) 中的所有元素,则返回 true

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";
    }

}

预期:“匹配”

实际:“不匹配”

我犯了什么错误吗?

【问题讨论】:

    标签: c++ stl


    【解决方案1】:

    不匹配,因为“needle”包含两个a,但“haystack”只有一个a

    另见:What does std::includes actually do?;另一种说法是set intersection 必须等于第二组。

    【讨论】:

      【解决方案2】:

      基于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;
      }
      

      当一个字符匹配时,第一个指针被压入。因此,您需要两个 a 字符,因为 Alaska 中有两个字符。

      向量中的额外a 可为您提供所需的结果:

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

      【讨论】:

        【解决方案3】:

        感谢您的回答。它帮助我理解了我的错误。

        我通过将阿拉斯加转换成一个集合解决了这个问题。

        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";
            }
        
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-09-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-09-28
          相关资源
          最近更新 更多