4.find_if查找

2021-05-05  本文已影响0人  lxr_
#include<iostream>
using namespace std;

#include<vector>
#include<algorithm>

//find_if(iterator begin, iterator end, _Pred);_Pred为函数或者谓词(返回bool类型的仿函数,根据仿函数的参数多少分为一元谓词和二元谓词)
//按值查找元素,找到返回指定位置的迭代器,找不到返回结束迭代器位置

//内置数据类型查找
class MyFind5
{
public:
    bool operator()(int val)//一元谓词
    {
        return val > 5;
        
    }
};
void test0401()
{
    vector<int> v;
    for (int i = 0; i < 10; i++)
    {
        v.push_back(i);
    }

    vector<int>::iterator it=find_if(v.begin(), v.end(), MyFind5());//查找val>5的,即用仿函数指定查找条件
    if (it == v.end())
    {
        cout << "未找到" << endl;
    }
    else
    {
        cout << "找到了" << (*it) << endl;
    }

}
//自定义数据类型查找
class Person
{
public:
    Person(string name,int age)
    {
        this->m_Name = name;
        this->m_Age = age;
    }
    string m_Name;
    int m_Age;
};
class FindPerson20
{
public:
    bool operator()(Person p)//一元谓词
    {
        return p.m_Age > 20;
        
    }
};
void test0402()
{
    vector<Person> v;

    Person p1("xan", 11);
    Person p2("si", 22);
    Person p3("fan", 33);

    v.push_back(p1);
    v.push_back(p2);
    v.push_back(p3);

    vector<Person>::iterator it=find_if(v.begin(), v.end(), FindPerson20());//利用仿函数指定查找年龄大于20岁的人
    if (it == v.end())
    {
        cout << "未找到" << endl;
    }
    else
    {
        cout << "找到了" << it->m_Name<<endl;
    }
}
int main()
{
    test0401();
    test0402();

    system("pause");
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读