C++ STL标准库:算法<algorithm> 比较是否相等 按条件是否相等 equal()

std::equal

简介:
如果两个序列的长度相同,并且对应元素都相等,equal() 算法会返回 true。

函数原型

equality (1)	template <class InputIterator1, class InputIterator2>
  				bool equal (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2);
predicate (2)	template <class InputIterator1, class InputIterator2, class BinaryPredicate>
  				bool equal (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, BinaryPredicate pred);

官方手册
http://www.cplusplus.com/reference/algorithm/equal/

使用示例:

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

void Origin(vector<int>& v)
{
	v.push_back(1);
	v.push_back(2);
	v.push_back(3);
	v.push_back(4);
	v.push_back(5);
	v.push_back(6);
	v.push_back(7);
}

void Origin2(vector<int>& v)
{
	v.push_back(3);
	v.push_back(4);
	v.push_back(5);
	v.push_back(6);
	v.push_back(7);
	v.push_back(8);
	v.push_back(9);
}

bool relationship(int e1, int e2)
{
	int tmp = e1 + 2;
	return  e2 == tmp;
}

void Print(vector<int>& v)
{
	vector<int>::iterator it;
	for (it = v.begin(); it != v.end(); it++)
		cout << *it << ",  ";
	cout << endl;
}

void main()
{
	vector<int> v1, v2;
	Origin(v1);
	Origin2(v2);

	cout << "vector v1: " << endl;
	Print(v1);
	cout << "vector v2: " << endl;
	Print(v2);

	bool eq = equal(v1.begin(), v1.end(), v2.begin());
	if (eq)
	{
		cout << "v1 == v2" << endl;
	}
	else
	{
		cout << "v1 != to v2" << endl;
	}

	bool eq2 = equal(v1.begin(), v1.end(), v2.begin(), relationship);
	if (eq2)
	{
		cout << "v2[i]==v1[i]+2" << endl;
	}
	else
	{
		cout << "v2[i]!=v1[i]+2" << endl;
	}
}

image-20201217154026838

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

超级D洋葱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值