c++中的find和find_if

STL的find,find_if函数提供了一种对数组、STL容器进行查找的方法。使用该函数,需包含头文件 #include <algorithm>。

总结

1、find_if针对查找的对象中包含指针需要进行比较

2、find则更偏向于普通的数值或者字符比较

3、两者都可以应用于自定义的类,只需在类中重载==运载符

find

我们查找一个list中的数据,通常用find(),例如:

#include <iostream>
#include <string>
#include <list>
using namespace std;

int main(){
   list<int> lst;
   lst.push_back(10);
   lst.push_back(20);
   lst.push_back(30);
   list<int>::iterator it = find(lst.begin(), lst.end(), 10);
   if (it != lst.end()){
        cout << *it << endl;
   }
   else{
        cout << "find nothing" << endl;
   }
   system("pause");
}

那么,如果容器里的元素是一个类呢?例如,有list<CPerson> ,其中CPerson类定义如下:

class CPerson{
pubilc:
     CPerson(void);
     ~CPerson(void);
private:
     int age;
};

那么如何用find()函数进行查找呢?这时,我们需要提供一个判断两个CPerson对象“相等”的定义,find()函数才能从一个list中找到与指定的CPerson“相等”的元素。
这个“相等”的定义,是通过重载“==”操作符实现的,我们在CPerson类中添加一个方法,定义为:

bool operator== (const CPerson& rhs) const;

实现为:

bool CPerson::operator== (const CPerson& rhs) const{
     return (age == rhs.age);
}

 然后我们就可以这样查找(假设list中已经有了若干CPerson对象)了:

list(CPerson) lst;
//向lst中添加元素,此处省略
CPerson cp_to_find;
cp_to_find.age = 50;
list<CPerson>::iterator it = find(lst.begin(), lst.end(), cp_to_find)

find_it

当有一个list<CPerson*>,这个list中的每一个元素都是一个对象的指针,我们要在这个list中查找具有指定age的元素,找到的话就得到对象的指针。不只是普通需要比较类型上的相等,而是两个对象的指针所对应的值进行比较,这时候,你不再能像上面的例子那样做。

我们需要用到find_if函数,并自己指定predicate function谓词函数(即find_if函数的第三个参数,请查阅STL手册)。先看看find_if函数的定义:
template<class InputIterator, class Predicate>
InputIterator find_if(InputIterator _First, InputIterator _Last, Predicate _Pred);
Parameters:
_First
An input iterator addressing the position of the first element in the range to be searched.
_Last
    An input iterator addressing the position one past the final element in the range to be searched.
_Pred
    User-defined predicate function object that defines the condition to be satisfied by the element being searched for. A predicate takes single argument and returns true or false.

 

我们在CPerson类外部定义这样一个结构体:

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

然后就可以利用find_if函数来查找了:

list(CPerson*) lst;
//向lst中添加元素,此处省略


list(CPerson*)::iterator it = find_it(lst.begin(), lst.end(), finder_t(50));

在这顺带说明一下()的函数调用符号()的重载,它只能通过类的成员来重载,

#include <iostream>
#include <string>
#include <list>
using namespace std;

class cls{
public:
     void operator() (){
          printf("helloworld!\n");
     }
     void operator() (const char* str){
          printf("%s", str);
     }
};

int main(void){
    cls cc;
    cc();
    cc("hellolinux\n");
    system("pause");
}

在main()函数中,cc是一个类,但是”cc();”这样的语法却是函数调用,在项目中这样的写法可以避免代码出现函数指针。

说白了,()其实就是函数指针的作用,代替了函数指针而已。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值