容器find_if函数定义和其第三个参数重载的疑问

容器find_if函数定义和其第三个参数重载的疑问,第1张

容器find_if函数定义和其第三个参数重载的疑问 - upendi - 博客园

容器find_if函数定义和其第三个参数重载的疑问

简单明了,这个是cpluscpus 对find_if的定义:

1
2
3
4
5
6
template<class InputIterator, class Predicate>
  InputIterator find_if ( InputIterator first, InputIterator last, Predicate pred )
  {
    for ( ; first!=last ; first++ ) if ( pred(*first) ) break;
    return first;
  }

【例1】对第三参数的处理例子,第三参数就是一函数名。。。


class CPerson
{
public:
 CPerson(int a)
 {
  age = a;
 }
public:
 int age; // 年龄
};

 struct finder_t
{
 finder_t(int n) : age(n)
 { }
 bool operator()(CPerson *p)
 { return (age == p->age); }
 int age;
};

int main(void)
{
 list<CPerson*> lst;
 CPerson a(10),b(20),c(30);

 lst.push_back(&a);
 lst.push_back(&b);
 lst.push_back(&c);

 //finder_t t(30);
// cout << finder_t(51) << endl;
 list<CPerson*>::iterator it = find_if(lst.begin(), lst.end(), finder_t(30)); // 查找年龄为50的人
 if (it != lst.end()) // 找到了
 {
  cout << "Found person with age : " << (*it)->age;
 }
 else // 没找到
 {
  cout <<"is not find!"<<endl;
 }
 getchar();
 return 0;
}

 

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/2083925.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-07-22
下一篇 2022-07-22

发表评论

登录后才能评论

评论列表(0条)

保存