C++ 算法 中的 equal函数

首页 / C++入门教程 / C++ 算法 中的 equal函数

C++算法equal()函数比较两个集合中的元素,如果发现两个集合中的所有元素都匹配,则返回一个真值。第一个参数从[first1,last1)开始,第二个参数从first2开始。

equal - 语法

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

equal - 参数

first1 :它是[first1,last1)的第一个元素的输入迭代器。

last1 :它是[first1,last1)的最后一个元素的输入迭代器。

first2 :它是[first2,last2)的第一个元素的输入迭代器。

pred :它是一个二进制函数,接受两个元素作为参数并执行该函数设计的任务。

equal - 返回值

如果两个集合中的所有元素都匹配,则该函数返回值true,否则返回false。

equal - 例子1

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
bool newpredicate(int m, int n)
{
	return(m==n);
}
int main()
{
	int newints[]={20,40,60,80,100};
	std::vector<int> newvector(newints, newints+5);
	if(std::equal(newvector.begin(),newvector.end(),newints))
	std::cout<<"Both the containers have matching elements.\n";
	else
	std::cout<<"Both the containers have difference elements.\n";
	newvector[3]=81;
	if(std::equal(newvector.begin(),newvector.end(),newints,newpredicate))
	std::cout<<"Both the containers have equal containers.\n";
	else
	std::cout<<"Both the containers do not have equal elements. \n";
	return 0;
}

输出:

Both the containers have matching elements.
Both the containers do not have equal elements.

equal - 例子2

#include<bits/stdc++.h>
using namespace std;
int main()
{
	int u1[]={10,20,30,40,50};
	std::vector<int> vec_1(u1,u1+sizeof(u1)/sizeof(int));
	std::cout<<"The vector consists of:";
	for(unsigned int k=0; k<vec_1.size(); k++)
	std::cout<<" "<<vec_1[k];
	std::cout<<"\n";
	if(std::equal(vec_1.begin(),vec_1.end(),u1))
	std::cout<<"Both the containers have equal elements.\n";
	else
	cout<<"Both containers have different elements.";
}

输出:

The vector consists of: 10, 20,30,40,50
Both the containers have equal elements.

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

Python核心技术与实战 -〔景霄〕

Redis核心技术与实战 -〔蒋德钧〕

实用密码学 -〔范学雷〕

说透5G -〔杨四昌〕

Serverless进阶实战课 -〔静远〕

Go进阶 · 分布式爬虫实战 -〔郑建勋〕

云原生架构与GitOps实战 -〔王炜〕

手把手带你搭建推荐系统 -〔黄鸿波〕

Midjourney入门实践课 -〔Jovi〕

好记忆不如烂笔头。留下您的足迹吧 :)