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



描述

C++ 函式std::algorithm::is_permutation() 測試一個序列是否為另一個序列的排列。它使用運算子 ==進行比較。

宣告

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

C++11

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

引數

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

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

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

返回值

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

異常

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

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

時間複雜度

二次。

示例

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

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

using namespace std;

int main(void) {
   vector<int> v1 = {1, 2, 3, 4, 5};
   vector<int> v2 = {5, 4, 3, 2, 1};
   bool result;

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

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

   v2[0] = 10;

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

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

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

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