C++ 算法库 - is_permutation() 函数


描述

C++ 函数std::algorithm::is_permutation()测试一个序列是否是其他序列的排列。它使用运算符 ==进行比较。

宣言

以下是 std::algorithm::is_permutation() 函数形式 std::algorithm 标头的声明。

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.
算法.htm