STL算法中仿函数使用

先看看STL中非组合式容器使用find算法一个例子:

#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
#include <stdio.h>
#include <string.h>
using namespace std;

int main()
{
    char index[10]= {0};
    vector<string> vc;
    vector<string>::iterator vc_iter;

    //向map中插入数据
    for(int i= 0;i< 10;i++)
    {
        memset(index,0,sizeof(index));
        sprintf(index,"index%d",i);
        vc.push_back(index);
    }

    //find可以比较是否存在指向值为“index5”的迭代器,如果存在则返回。
    //这是一般情况下find函数的使用方法。
    if(vc.end()!= (vc_iter= find(vc.begin(),vc.end(),"index5")))
    {
        cout<< (*vc_iter).c_str()<< endl;
    }
    return 1;
}

但如果容器换成了组合式容器(如map),或者容器中出现更复杂的结构或者直接存放的就是指针呢?如:map<char *, int>或者 map<pair<string,int >,string >

出现这种情况该怎么使用find函数呢?显然,一些自定义的结构要比较时必定要调用到自己编写的比较函数,而STL中算法find_if就能传入你自定义的比较函数,这个比较函数也就是STL中所谓的仿函数。请看以下例子:

#include <algorithm>
#include <iostream>
#include <map>
#include <string>

using namespace std;

//自定义结构体
struct info
{
    int num;
    string name;
    info(int num_,string name_):num(num_),name(name_){}
    info(const info &info_):num(info_.num),name(info_.name){}
    //map中first元素需要的比较函数
    bool operator< (const info &other) const
    {   
       return this->num< other.num;
    }
    //重载括号运算符,find_if通过调用此函数比较大小
    bool operator()(map<info,int>::value_type &find_)
    {
        return (find_.first.num== this->num && find_.first.name== this->name);
    }
};

int main()
{
    map<info,int> mp;
    map<info,int>::iterator mp_iter;

    //向map中插入数据
    for(int i= 0;i< 10;i++)
    {
        mp.insert(make_pair(info(i,"index"),i));
    }

    //find_if通过调用info匿名对象重载的括号运算符函数来比较
    //是否存在指向值为info(5,"index5")的迭代器,如果存在则返回。
    if(mp.end()!= (mp_iter= find_if(mp.begin(),\
        mp.end(),info(5,"index"))))
    {
        cout<< mp_iter->first.num<< "\t" << mp_iter->first.name.c_str() \
        <<"\t"<< mp_iter->second<< endl;
    }
    return 1;
}

未完待续!!!

点赞