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

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

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

      函数原型:

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

    示例代码:

/*******************************************************************
 * Copyright (C) Jerry Jiang
             
 * File Name   : adjacent_find.cpp
 * Author      : Jerry Jiang
 * Create Time : 2011-9-30 22:07:22
 * Mail        : jbiaojerry@gmail.com
 * Blog        : http://blog.csdn.net/jerryjbiao               
 * Description :  简单的程序诠释C++ STL算法系列之四              
 *                非变易算法 : 邻近查找容器元素adjacent_find              
 ******************************************************************/

#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;
}

*******************************************************************************************************************************

C++经典书目索引及资源下载:http://blog.csdn.net/jerryjbiao/article/details/7358796

********************************************************************************************************************************



 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值