[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》
相关文章推荐
- [C/C++标准库]_[初级]_[函数对象functor的使用]
- [C/C++标准库]_[初级]_[使用ctype里的isxxx函数时要注意的事项]
- [C/C++标准库]_[初级]_[使用ctype里的isxxx函数时要注意的事项]
- c++中优化内存分配:new/delete操作符;allocator类对象的使用;operator new/operator delete函数及定位new表达式
- 【C++】boost::bind和函数对象一起使用实现便捷的异步编程
- [C/C++标准库]_[初级]_[如何实现std::string自己的Format(sprintf)函数]
- [C/C++]_[初级]_[使用C字符串(或者std::string)处理函数获取文件所在目录
- 从零开始学C++之对象的使用(一):static 成员变量、static 成员函数、类/对象的大小
- [C/C++标准库]_[初级]_[使用fstream合并文本文件]
- 【C++学习笔记】使用控制符及流对象的成员函数控制输出格式
- [C/C++标准库]_[初级]_[不使用正则替换和删除字符串]
- C++中函数对象(仿函数)的使用
- 一个sample学会使用c++比较函数对象和hash函数对象
- [C/C++标准库]_[初级]_[使用fstream合并文本文件]
- [C/C++标准库]_[初级]_[不使用正则替换和删除字符串]
- [C/C++标准库]_[初级]_[使用freopen重定向标准输出]
- 从零开始学C++之对象的使用(一):static 成员变量、static 成员函数、类/对象的大小
- [C/C++标准库]_[初级]_[优先队列priority_queue的使用]
- C++ 运算符重载之把类对象当着函数名使用
- [C/C++标准库]_[初级]_[使用freopen重定向标准输出]