您的位置:首页 > 编程语言 > C语言/C++

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

2018-03-24 14:53 253 查看
//----------------------------------------------------------------------------------------  
//      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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  stl