當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ Algorithm is_permutation()用法及代碼示例


描述

C++ 函數std::algorithm::is_permutation()測試一個序列是否是其他序列的排列。它用二元謂詞用於比較。

聲明

以下是 std::algorithm::is_permutation() 函數形式 std::algorithm 頭文件的聲明。

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。

返回值

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

異常

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

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

時間複雜度

二次方。

示例

下麵的例子展示了 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.

相關用法


注:本文由純淨天空篩選整理自 C++ Algorithm Library - is_permutation() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。