泛型演算法之is_permutation
阿新 • • 發佈:2018-12-21
檢測兩個區間,在不考慮數序的的情況下的相等性。
bool is_permutation (ForwardIterator1 beg1, ForwardIterator1 end1,ForwardIterator2 beg2);
bool is_permutation (ForwardIterator1 beg1, ForwardIterator1 end1,ForwardIterator2 beg2,CompFunc op);
- 兩種情況都返回在不考慮順序的情況下,第一個區間是否與第二個區間相等,第一種情況使用“==”比較,第二種情況使用返回bool的二元謂語op比較。
- op不應該在函式執行過程中改變引數的值,也不應在函式執行過程中改變狀態。
- 所有的迭代器都應指向相同的型別。
- 這裡的op必須是對稱、自反且可傳遞的。
例:
#include <vector> #include <list> #include <algorithm> #include <iostream> #include <iterator> #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() { 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; }
輸出結果:1 0
coll1 and coll2 have equal elements
numbers of even and odd elements match