泛型算法之is_permutation

检测两个区间,在不考虑数序的的情况下的相等性。

bool is_permutation (ForwardIterator1 beg1, ForwardIterator1 end1,ForwardIterator2 beg2);

bool is_permutation (ForwardIterator1 beg1, ForwardIterator1 end1,ForwardIterator2 beg2,CompFunc op);

 

  1. 两种情况都返回在不考虑顺序的情况下,第一个区间是否与第二个区间相等,第一种情况使用“==”比较,第二种情况使用返回bool的二元谓语op比较。
  2. op不应该在函数运行过程中改变参数的值,也不应在函数运行过程中改变状态。
  3. 所有的迭代器都应指向相同的类型。
  4. 这里的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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值