C++ 算法 中的 adjacent_find函数

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

C++算法neighbor_find()函数在两个连续匹配元素的最先出现的参数[first,last]上执行搜索操作。如果找到这样的元素,则返回两个元素的第一个元素的迭代器。否则,返回最后一个元素。

adjacent_find - 语法

template<class ForwardIterator>
ForwardIterator adjacent_find(ForwardIterator first, ForwardIterator last);

template<class ForwardIterator, class BinaryPredicate>
ForwardIterator adjacent_find(ForwardIterator first,ForwardIterator last BinaryPredicate pred);

adjacent_find - 参数

第一:它是参数中第一个元素的正向迭代器。

最后:它是参数中最后一个元素的前向迭代器。

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

adjacent_find - 返回值

如果找到两个连续的匹配元素,则该函数将迭代器返回到range [first,last)的第一个元素,否则返回最后一个元素。

链接:https://www.learnfk.comhttps://www.learnfk.com/c++/cpp-algorithm-adjacent-find-function.html

来源:LearnFk无涯教程网

adjacent_find - 例子1

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
bool myfunc(int j, int k)
{
	return(j==k);
}


int main()
{
	int newints[]={5,20,5,50,50,20,60,60,20};
	std::vector<int> newvector(newints, newints+8);
	std::vector<int>::iterator ti;
	ti=std::adjacent_find(newvector.begin(),newvector.end());
	if(ti!=newvector.end())
	std::cout<<"In the given range the first pair of sequence that is repeated is:"<<*ti<<"\n";
	ti=std::adjacent_find(++ti,newvector.end(),myfunc);
	if(ti!=newvector.end())
	std::cout<<"In the given range the second pair of sequence 	that is repeated is:"<<*ti<<"\n";
	return 0;
}

输出:

In the given range the first pair of sequence that is repeated are: 50
In the given range the second pair of sequence that is repeated are: 60

adjacent_find - 例子2

#include<iostream>
#include<algorithm>
int main()
{
	int A[]={12,14,17,17,19};
	int n=sizeof(A)/sizeof(A[0]);
	int* ti=std::adjacent_find(A,A+n);
	std::cout<<*ti;
}

输出:

17

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

技术教程推荐

10x程序员工作法 -〔郑晔〕

趣谈Linux操作系统 -〔刘超〕

Service Mesh实战 -〔马若飞〕

Serverless入门课 -〔蒲松洋(秦粤)〕

分布式系统案例课 -〔杨波〕

Vim 实用技巧必知必会 -〔吴咏炜〕

结构执行力 -〔李忠秋〕

手把手带你写一个 MiniTomcat -〔郭屹〕

互联网人的数字化企业生存指南 -〔沈欣〕

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