find_if在类里的应用

纠结我好久的find_if在类里的应用,终于弄明白了。
其实就是第三个参数难倒了我。
原型如下
template<class InputIterator, class Predicate>
InputIterator find_if(InputIterator _First, InputIterator _Last, Predicate _Pred);

注意find_if不属于vector的成员,而存在于算法中,应加上头文件
#include < algorithm>
参数三就是需要给它写一个类,在该类里找到我们要找的值

下面展示一些 代码。

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
class Student
{
	public:
 	string Name;
    int Age;
    int Num;
    Student(int num, string name, int age)
    {
        Num = num;
        Name = name;
        Age = age;
    }
};

typedef struct finder_t
{
    finder_t(int n) : num(n) {}
    bool operator()(Student &s)
    {
        return (s.Num==num);
    }
    int num;
}finder_t;

int main()
{
	vector<Student> v;
    vector<Student>::iterator aim;
	Student s1(1001,"李华",18);
    Student s2(1002,"小明",20);
    Student s3(1003,"张三",17);
    Student s4(1004,"李四",21);
    Student s5(1005,"王五",16);
    v.push_back(s1);
    v.push_back(s2);
    v.push_back(s3);
    v.push_back(s4);
    v.push_back(s5);
    int a;
    cin>>a;
    aim = find_if(v.begin(), v.end(), finder_t(a));
    if (aim != v.end())
       {
           cout << "该学生信息为"<<endl;
           cout <<"学号:"<< aim->Num << " 姓名:" << aim->Name << " 年龄:" << aim->Age << endl;
       }
}

如果您需要更详细点的,详情请见:https://blog.csdn.net/zzhongcy/article/details/87709685.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值