您的位置:首页 > 编程语言 > C语言/C++

[C/C++标准库]_[初级]_[函数对象functor的使用]

2014-04-19 15:07 399 查看

Functor

std::set

场景:

1. functor其实就是一个类对象,因为它重载了operator()操作符,所以可以把实例当作函数名那样操作,在C里也只有函数可以这么做.比如语句 f(1,2);在cpp

必须通过上下文判断f是对象还是函数.

2.在使用stl的容器类或算法函数时,经常需要自己传入一个functo作为参数或模板.

#include <string.h>

#include <iostream>
#include <fstream>
#include <string>
#include <utility>
#include <set>

using namespace std;

class Person
{
public:
Person(int code,const string& name,const string& grade,
const string& address):code_(code)
{
name_ = name;
grade_ = grade;
address_ = address;
}
~Person(){}
int code_;// 学号.
string name_;// name.
string grade_; //grade.
string address_;

void operator()()
{
cout << " code_: " << code_
<< " name_: " << name_
<< " grade_: " << grade_
<< " address_: " << address_
<< endl;
}
};

class PersonCompare
{
public:
bool operator() (const Person* p1, const Person* p2) const
{
return p1->code_ < p2->code_;
}
/* data */
};

class test_functor
{
public:
void operator()(int x,int y)
{
cout << "x+y: " << x+y << endl;
}

/* data */
};

int main(int argc, char const *argv[])
{
//1.simple functor
test_functor tf;
tf(1,2);

//2.sort functor
typedef set<Person*,PersonCompare> PersonSet;
PersonSet::iterator it;
PersonSet ps;
ps.insert(new Person(3,"张三","高三(1)班","北京朝阳区"));
ps.insert(new Person(2,"李四","高三(2)班","北京海淀区"));
ps.insert(new Person(1,"龙五","高三(3)班","北京王府井"));
// ps.insert(new Person(1,"龙四","高三(3)班","北京王府井"));

for (it = ps.begin(); it != ps.end(); ++it)
{
(*(*it))();
}

cout << endl;
pair<PersonSet::iterator,bool> res = ps.insert(new Person(1,"张四","高三(3)班","北京王府井"));
if (!res.second)
{
cout << "insert fail,exist name: " << (*(res.first))->name_ << endl;
}
for (it = ps.begin(); it != ps.end(); ++it)
{
(*(*it))();
}

return 0;
}


输出:

x+y: 3
code_: 1 name_: 龙五 grade_: 高三(3)班 address_: 北京王府井
code_: 2 name_: 李四 grade_: 高三(2)班 address_: 北京海淀区
code_: 3 name_: 张三 grade_: 高三(1)班 address_: 北京朝阳区

insert fail,exist name: 龙五
code_: 1 name_: 龙五 grade_: 高三(3)班 address_: 北京王府井
code_: 2 name_: 李四 grade_: 高三(2)班 address_: 北京海淀区
code_: 3 name_: 张三 grade_: 高三(1)班 address_: 北京朝阳区
[Finished in 0.1s]


参考:

1.《C++ Standard Library, The: A Tutorial and Reference》
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐