/*
* find //查找元素
find_if //按条件查找元素
adjacent_find //查找相邻重复元素
binary_search //二分查找法
count //统计元素个数
count_if //按条件统计元素个数
=====================================
功能描述:
查找指定元素,找到返回指定元素的迭代器,找不到返回结束迭代器end()
函数原型:
find(iterator beg, iterator end, value);
// 按值查找元素,找到返回指定位置迭代器,找不到返回结束迭代器位置
// beg 开始迭代器
// end 结束迭代器
// value 查找的元素
*/
#include<iostream>
#include <set>
#include <functional>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
class greateFive
{
public:
bool operator()(int val)
{
return val>5;
}
};
void test01()
{
vector<int>v;
for (int i=0;i<10;i++)
{
v.push_back(i);
}
//查找容器中是否有5这个元素
vector<int>::iterator it=find_if(v.begin(),v.end(),greateFive());//匿名函数对象
if (it!=v.end())
{
cout<<"找到第一个大于5元素"<<*it<<endl;
}
}
//自定义数据类型
class Person
{
public:
Person(string name,int age);
public:
string m_Name;
int m_age;
};
class Greate20
{
public:
bool operator()(Person &p)
{
return p.m_age>20;
}
};
Person::Person(string name, int age)
{
m_Name=name;
m_age=age;
}
void test02()
{
vector<Person> v;
//创建数据
Person p1("aaa",10);
Person p2("bbb",20);
Person p3("ccc",30);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
vector<Person>::iterator it=find_if(v.begin(),v.end(),Greate20());
if (it!=v.end())
{
cout<<"找到p2元素"<<endl;
cout<<"名字"<<it->m_Name<<endl;
cout<<"年龄"<<it->m_age<<endl;
}
}
int main(void)
{
test01();
test02();
system("pause");
return 0;
}
/*
总结:find_if按条件查找使查找更加灵活,提供的仿函数可以改变不同的策略.
-----------------------------------------------------------------
找到第一个大于5元素6
找到p2元素
名字ccc
年龄30
请按任意键继续. . .
*/
002find_if()查找算法
猜你喜欢
转载自blog.csdn.net/baixiaolong1993/article/details/89645515
今日推荐
周排行