STL is_permutation函数

STL is_permutation函数算法

STL 中的 is_permutation() 算法可以用来检查一个序列是不是另一个序列的排列,如果是,会返回 true。

STL is_permutation函数详解

头文件

#include <algorithm>

语法

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

参数

参数 描述
first1 输入迭代器
last1 输入迭代器
first2 输入迭代器
pred 自定义比较规则

案例

STL is_permutation函数

使用 STL is_permutation 函数判断集合

#include <vector> #include <list> #include <algorithm> #include <iostream> #include <iterator> #include <deque> #include <functional> using namespace std; bool fun(int n,int m) { return (n == m * 2); } bool bothEvenOrOdd(int elem1, int elem2) { return elem1 % 2 == elem2 % 2; } int main() { std::cout << "嗨客网(www.haicoder.net)\n" << std::endl; vector<int>v{ 1,2,3,4 }; list<int>lst{ 4,3,1,2,1}; list<int>lst1{4,2,6,8}; cout << is_permutation(v.begin(), v.end(), lst.begin())<<ends; cout << is_permutation(v.begin(), v.end(), lst1.begin(),fun) << endl; vector<int> coll1; list<int> coll2; deque<int> coll3; coll1 = { 1, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; coll2 = { 1, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; coll3 = { 12, 11, 13, 19, 18, 17, 16, 15, 14, 11 }; if (is_permutation(coll1.cbegin(), coll1.cend(), coll2.cbegin())) { cout << "coll1 and coll2 have equal elements" << endl; } else { cout << "coll1 and coll2 don’t have equal elements" << endl; } if (is_permutation(coll1.cbegin(), coll1.cend(), coll3.cbegin(), bothEvenOrOdd)) { cout << "numbers of even and odd elements match" << endl; } else { cout << "numbers of even and odd elements don’t match" << endl; } return 0; }

我们在 Linux 下使用 g++ 进行编译,具体命令如下:

g++ is_permutation.cpp -std=c++11

编译后,我们直接运行生成的二进制文件 a.out,如下图所示:

37_STL is_permutation函数.png

我们使用了 is_permutation 函数,对集合进行了检查。

STL is_permutation函数总结

STL 中的 is_permutation() 算法可以用来检查一个序列是不是另一个序列的排列,如果是,会返回 true。