简单的程序诠释C++ STL算法系列之四:adjacent_find

  C++STL的非变易算法(Non-mutating algorithms)是一组不破坏操作数据的模板函数,用来对序列数据进行逐个处理、元素查找、子序列搜索、统计和匹配。

      adjacent_find算法用于查找相等或满足条件的邻近元素对。其有两种函数原型:一种在迭代器区间[first , last)上查找两个连续的元素相等时,返回元素对中第一个元素的迭代器位置。另一种是使用二元谓词判断binary_pred,查找迭代器区间[first , last)上满足binary_pred条件的邻近元素对,未找到则返回last。

      函数原型:

[cpp]  view plain copy
  1. <strong>template<class ForwardIterator>  
  2.    ForwardIterator adjacent_find(  
  3.       ForwardIterator _First,   
  4.       ForwardIterator _Last  
  5.       );  
  6. template<class ForwardIterator , class BinaryPredicate>  
  7.    ForwardIterator adjacent_find(  
  8.       ForwardIterator _First,   
  9.       ForwardIterator _Last,   
  10.             BinaryPredicate _Comp  
  11.    );  
  12. </strong>  

    示例代码:


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

using namespace std;

//判断X和y是否奇偶同性
bool Parity_Equal(int x, int y)
{
	return (x - y) % 2 == 0 ? 1 : 0;
}

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(), Parity_Equal);
	if (iResult != iList.end())
	{
		cout << "链表中第一对奇偶相同的元素为:" << endl;
		cout << *iResult++ << endl;
		cout << *iResult << endl;
	}
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值