adjacent_find

本文详细解释了C++中用于寻找相邻元素的`adjacent_find`函数,包括其工作原理、使用方法及两个实例代码演示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Protype of function is

template<class ForwardIterator>
   ForwardIterator adjacent_find(
      ForwardIterator _First, 
      ForwardIterator _Last
      );
template<class ForwardIterator , class BinaryPredicate>
   ForwardIterator adjacent_find(
      ForwardIterator _First, 
      ForwardIterator _Last, 
            BinaryPredicate _Comp
   );
One example,

#include <algorithm>
#include <list>
#include <iostream>

using namespace std;

int main(){
	list<int> iList;
	iList.push_back(3);
	iList.push_back(6);
	iList.push_back(9);
	iList.push_back(11);
	iList.push_back(11);
	iList.push_back(18);
	iList.push_back(20);
	iList.push_back(20);

	list<int>::iterator iter;
	for(iter = iList.begin(); iter != iList.end(); ++iter){
		cout << *iter << "  ";
	}
	cout << endl;

	list<int>::iterator iResult = adjacent_find(iList.begin(), iList.end());
	if (iResult != iList.end()){
		cout << "链表中第一对相等的邻近元素为:" << endl;
		cout << *iResult++ << endl;
		cout << *iResult << endl;
	}

	iResult = adjacent_find(iList.begin(), iList.end(), [](int x, int y){return (x - y) % 2 == 0 ? 1 : 0;});
	if (iResult != iList.end()){
		cout << "First pair with same parity:" << endl;
		cout << *iResult++ << endl;
		cout << *iResult << endl;
	}
	return 0;
}
Note that *iResult++, first outputs *iResult, then add one to iResult.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值