函数适配器

#include <iostream>
#include <algorithm>
#include <functional>
#include <string>
#include <vector>

using namespace std;


class Person
{
    public:
        Person(const string &name):name_(name) {}
        void Print() const { cout<<name_<<endl; }
        void PrintWithPrefix(string prefix) const {cout<<prefix<<" "<<name_<<endl;}
    private:
        string name_;
};

void foo(const vector<Person> &v)
{
    for_each(v.begin(),v.end(),mem_fun_ref(&Person::Print));
    for_each(v.begin(),v.end(),bind2nd(mem_fun_ref(&Person::PrintWithPrefix),"person"));
}

void foo2(const vector<Person*> &v)
{
    for_each(v.begin(),v.end(),mem_fun(&Person::Print));
    for_each(v.begin(),v.end(),bind2nd(mem_fun(&Person::PrintWithPrefix),"Person"));
}


int main()
{
    vector<Person> v;
    v.push_back(Person("tom"));
    v.push_back(Person("jerry"));
    foo(v);

    vector<Person*> v2;
    v2.push_back(new Person("tom"));
    v2.push_back(new Person("jerry"));
    foo2(v2);

    return 0;
}
#include <iostream>
#include <algorithm>
#include <string>
#include <functional>
#include <string>
#include <vector>
#include <string.h>


using namespace std;

int main(void)
{
    char *a[] = {"","BBB","CCC"};
    vector<char*> v(a,a+2);
    vector<char*>::iterator ite;
    ite = find_if(v.begin(),v.end(),bind2nd(ptr_fun(strcmp),""));
    if(ite != v.end())
    {
        cout<<*ite<<endl;
    }
    return 0;
}
#include <iostream>
#include <string>
#include <stdlib.h>
#include <algorithm>
#include <vector>


using namespace std;


bool check(int elem)
{
    return elem < 3;

}

int main(void)
{
    int a[] = {1,2,3,4,5};
    vector<int> v(a,a+5);
    
    vector<int>::iterator ite;
    ite = find_if(v.begin(),v.end(),not1(ptr_fun(check)));
    if(ite != v.end())
    {
        cout<<*ite<<endl;
    }
    return 0;
}

你可能感兴趣的:(函数适配器)