C++STL之查找重复值的算法

//----------------------------------------------------------------------------------------  
//      Desc:       STL adjacent_find() used in struct data  
//      Author:     spring brother  
//      Data:       2018.3.24  
//      Copyright (C) 2018 spring brother  
//----------------------------------------------------------------------------------------  

/*
查找重复值的算法
adjacent_find(beg,end)
adjacent_find(beg,end,binaryPred)

返回指向第一对相邻重复元素的迭代器。如果序列中无相邻重复元素则返回end。

search_n(beg,end,count,val)
search_n(beg,end,count,val,binayrPred)

返回一个迭代器,从此位置开始有count个相等元素。如果序列中不存在这样的子序列,则返回end。

注意:adjacent_find可用于查找拥有倍数关系的相邻元素,而search_n只能用于查找数值相等的相邻元素。
另外,search_n的仿函数及匿名函数的参数不能为引用类型。
*/
#include "stdafx.h"
#include <algorithm>
#include <iostream>

using namespace std;

bool isEqual(int &i,int &j) {
return 2*i == j;
}
bool ifEqual(int i, int j) {  //search_n的仿函数及匿名函数的参数不能为引用类型
return i == j;
}
int main()
{
int arrIn[6] = { 1,2,4,4,4,5 };
int *temp = adjacent_find(arrIn, arrIn + 6);  //adjacent_find
if (temp != arrIn + 6) {
cout << "adjacent_find = " << *temp << endl;
}
temp = adjacent_find(arrIn, arrIn + 6, isEqual);  //adjacent_find,传入仿函数
if (temp != arrIn + 6) {
cout << "adjacent_find = " << *temp << endl;
}
temp = adjacent_find(arrIn, arrIn + 6, [](int &i, int &j) {return 2 * i == j; });  //adjacent_find,传入匿名函数
if (temp != arrIn + 6) {
cout << "adjacent_find = " << *temp << endl;
}

int count = 3;
int val = 4;
temp = search_n(arrIn, arrIn + 6, count, val);   //search_n
if (temp != arrIn + 6) {
cout << "search_n = " << *temp << endl;
}
temp = search_n(arrIn, arrIn + 6, count, val, ifEqual);  //search_n,传入仿函数
if (temp != arrIn + 6) {
cout << "search_n = " << *temp << endl;
}
temp = search_n(arrIn, arrIn + 6, count, val, [](int i,int j) {return i == j; });  //search_n,传入匿名函数
if (temp != arrIn + 6) {
cout << "search_n = " << *temp << endl;
}

    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值