Person p2("bbb", 20);
Person p3("ccc", 30);
var.push_back(p1);
var.push_back(p2);
var.push_back(p3);
vector<Person>::iterator pos = find(var.begin(), var.end(), p1);
if (pos != var.end())
cout << "找到姓名: " << (*pos).m_name << endl;
system("pause");
return 0;
}
7.4 条件查找容器元素
Find_if 算法函数,用于查找序列中满足指定条件的第一个元素,并返回该元素的迭代器。find_if的用法如下:
template<class InputIterator, class UnaryPredicate>
InputIterator find_if(InputIterator first, InputIterator last, UnaryPredicate pred);
其中,first、last
是迭代器,表示待查找的序列的范围;pred
是一个一元谓词函数,用于指定查找条件。调用find_if
函数后,将会在[first, last]
区间中查找第一个谓词pred
返回true的元素,并将该元素的迭代器作为函数返回值返回。如果未找到满足条件的元素,则函数将返回last。
与上方的普通查找相比,该查找可以添加回调函数,用于对查到的数据进行筛选和过滤操作,如下所示案例中寻找第一个被5整除的元素。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool MyFunction(int x) { return x % 5 ? 0 : 1; }
int main(int argc, char* argv[])
{
vector<int> var(20);
// 循环生成数据
for (unsigned int x = 0; x < var.size(); x++)
var[x] = (x + 1) * (x + 3);
// 循环遍历,并判断是否符合条件
vector<int>::iterator it = find_if(var.begin(),var.end(),MyFunction);
if (it != var.end())
{
// 寻找第一个被5整除的元素
cout << *it << endl;
cout << "元素索引: " << it - var.begin() << endl;
}
system("pause");
return 0;
}
7.5 条件查找类容器元素
Find_if 算法函数,用于查找序列中满足指定条件的第一个元素,并返回该元素的迭代器。find_if的用法如下:
template<class InputIterator, class UnaryPredicate>
InputIterator find_if(InputIterator first, InputIterator last, UnaryPredicate pred);
其中,first、last
是迭代器,表示待查找的序列的范围;pred
是一个一元谓词函数,用于指定查找条件。调用find_if
函数后,将会在[first, last]
区间中查找第一个谓词pred
返回true的元素,并将该元素的迭代器作为函数返回值返回。如果未找到满足条件的元素,则函数将返回last。
如下一个案例中,实现了查询Person
类中的特定数据,查找ptr
中的数据是否存在于我们的结构中。
#include <iostream>
#include <vector>
#include <string>
#include <functional>
#include <algorithm>
using namespace std;
class Person
{
public:
string m_name;
int m_age;
public:Person(string name, int age){
this->m_name = name;
this->m_age = age;
}
public: bool operator==(const Person &p){
// 重载 == 实现遍历数据
if (this->m_name == p.m_name && this->m_age == p.m_age)
return true;
return false;
}
};
// 使用binary_function适配函数实现传递两个Person数据
class MyCompare:public binary_function<Person *,Person *,bool>
{
public: bool operator()(Person *p1,Person *p2) const {
// 对比函数,重载() 用于实现指针元素的对比
if (p1->m_name == p2->m_name && p1->m_age == p2->m_age)
return true;
return false;
}
};
int main(int argc, char* argv[])
{
vector<Person *> var;
Person p1("aaa", 10);
Person p2("bbb", 20);
Person p3("ccc", 30);
var.push_back(&p1);
var.push_back(&p2);
var.push_back(&p3);
// 查找这个属性的类成员
Person *ptr = new Person("bbb", 20);
// 通过使用bind2nd绑定事件,将ptr传递给MyCompare() 即可实现两个类属性的对比查找
vector<Person *>::iterator pos = find_if(var.begin(), var.end(), bind2nd(MyCompare(),ptr));
if (pos != var.end())
cout << "找到姓名: " << (*pos)->m_name << endl;
system("pause");
return 0;
}
7.6 邻近查找容器元素
Adjacent_find 算法函数,用于查找相邻元素的第一个出现位置。adjacent_find的用法如下:
template<class InputIterator>
InputIterat