find_if(iterator beg, iterator end, _Pred);
按值查找元素,找到返回指定位置迭代器,找不到
则返回结束迭代器位置
_Pred:函数或谓词(返回bool类型的仿函数)
#include <iostream>
#include <string>
#include <vector>
#include <deque>
#include <algorithm>
#include <list>
#include <set>
#include <map>
#include <functional>
using namespace std;
//内置数据类型
void test1()
{
vector<int> vt;
vt.push_back(10);
vt.push_back(20);
vt.push_back(30);
vt.push_back(40);
//查询传入的值是否存在
vector<int>::iterator it = find(vt.begin(), vt.end(), 30);
if (it != vt.end())
{
cout<<"找到:"<<*it<<endl;
}
else
{
cout<<"没有找到"<<endl;
}
}
//自定义数据类型
class Person
{
public:
Person(string name, int age):m_name(name), m_age(age){}
bool operator==(const Person p)
{
if (this->m_name == p.m_name && this->m_age == p.m_age)
{
return true;
}
return false;
}
string m_name;
int m_age;
};
void test2()
{
vector<Person> vt;
Person p1("刘备", 38);
Person p2("关羽", 35);
Person p3("张飞", 30);
Person p4("赵云", 28);
vt.push_back(p1);
vt.push_back(p2);
vt.push_back(p3);
vt.push_back(p4);
Person p5("赵云", 28);
//第三个参数传入的是一个对象类型,查询传入的对象是否存在
vector<Person>::iterator it = find(vt.begin(), vt.end(), p5);
if (it != vt.end())
{
cout<<"找到:"<<it->m_name<<","<<it->m_age<<endl;
}
else
{
cout<<"没有找到"<<endl;
}
}
class MyCompare{
public:
bool operator()(int var)
{
return var>5;
}
};
//内置类型
void test3()
{
vector<int> vt;
for (int i=0; i<10; i++)
{
vt.push_back(i);
}
//条件查询,找到符合条件的第一个元素,不仅仅是比较,也可以==等运算符, 传入的是一个仿函数对象
vector<int>::iterator it = find_if(vt.begin(), vt.end(), MyCompare());
if (it != vt.end())
{
cout<<"找到:"<<*it<<endl;
}
else
{
cout<<"未找到"<<endl;
}
}
//自定义数据类型
class MyCompare1
{
public:
bool operator()(const Person p)
{
if (p.m_age >40)
{
return true;
}
return false;
}
string m_name;
int m_age;
};
void test4()
{
vector<Person> vt;
Person p1("刘备", 38);
Person p2("关羽", 35);
Person p3("张飞", 30);
Person p4("赵云", 28);
vt.push_back(p1);
vt.push_back(p2);
vt.push_back(p3);
vt.push_back(p4);
//条件查询,仿函数定义查询条件
vector<Person>::iterator it = find_if(vt.begin(), vt.end(), MyCompare1());
if (it != vt.end())
{
cout<<"找到:"<<it->m_name<<","<<it->m_age<<endl;
}
else
{
cout<<"没有找到"<<endl;
}
}
void test5()
{
vector<int> vt;
vt.push_back(10);
vt.push_back(20);
vt.push_back(30);
vt.push_back(40);
vt.push_back(40);
//查找容器中相邻相同的元素,返回第一个元素的迭代器
vector<int>::iterator it = adjacent_find(vt.begin(), vt.end());
if (it != vt.end())
{
cout<<"找到:"<<*it<<endl;
cout<<"找到:"<<*(it+1)<<endl;
}
else
{
cout<<"没有找到"<<endl;
}
}
int main()
{
test1();
test2();
test3();
test4();
}