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



描述

C++ 函式std::algorithm::is_permutation()測試一個序列是否為另一個序列的排列。它使用二元謂詞進行比較。

宣告

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

C++11

template <class ForwardIterator1, class ForwardIterator2, class BinaryPredicate>
bool is_permutation(ForwardIterator1 first1, ForwardIterator1 last1,
   ForwardIterator2 first2, BinaryPredicate pred);

引數

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

  • last1 − 第一個序列的結束位置的輸入迭代器。

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

  • pred − 一個接受兩個引數並返回 bool 值的二元謂詞。

返回值

如果第一個範圍是另一個範圍的排列,則返回 true;否則返回 false。

異常

如果二元謂詞或迭代器上的操作丟擲異常,則丟擲異常。

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

時間複雜度

二次方。

示例

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

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

using namespace std;

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

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

   result = is_permutation(v1.begin(), v1.end(), v2.begin());

   if (result == false)
      cout << "Both vector doesn't contain same elements." << endl;

   result = is_permutation(v1.begin(), v1.end(), v2.begin(), ignore_case);

   if (result == true)
      cout << "Both vector contains same elements." << endl;

   return 0;
}

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

Both vector doesn't contain same elements.
Both vector contains same elements.
algorithm.htm
廣告