C++ 演算法庫 - includes() 函式



描述

C++ 函式std::algorithm::includes() 測試第一個集合是否為另一個集合的子集。此成員函式期望元素按排序順序排列。它使用二元函式進行比較。

宣告

以下是來自 std::algorithm 標頭檔案的 std::algorithm::includes() 函式的宣告。

C++98

template <class InputIterator1, class InputIterator2, class Compare>
bool includes(InputIterator1 first1, InputIterator1 last1,
   InputIterator2 first2, InputIterator2 last2, Compare comp);

引數

  • first1 - 第一個序列的初始位置的輸入迭代器。

  • last1 - 第一個序列的最終位置的輸入迭代器。

  • first2 - 第二個序列的初始位置的輸入迭代器。

  • last2 - 第二個序列的最終位置的輸入迭代器。

  • comp - 一個接受兩個引數並返回 bool 值的二元函式。

返回值

如果第一個集合是另一個集合的子集,則返回 true,否則返回 false。

異常

如果元素比較或迭代器上的操作丟擲異常,則丟擲異常。

請注意,無效引數會導致未定義的行為。

時間複雜度

線性。

示例

以下示例演示了 std::algorithm::includes() 函式的使用方法。

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

bool compare(char a, char b) {
   return (tolower(a) == tolower(b));
}

int main(void) {
   vector<char> v1 = {'a', 'b', 'c', 'd', 'e'};
   vector<char> v2 = {'C', 'D', 'E'};
   bool result;

   result = includes(v1.begin(), v1.end(), v2.begin(), v2.end(), compare);

   if (result == true)
      cout << "Vector v2 is subset of v1" << endl;

   return 0;
}

讓我們編譯並執行以上程式,這將產生以下結果:

Vector v2 is subset of v1
algorithm.htm
廣告