所谓仿函数,从字面意思来说就是类似函数的形式,定义为:通过重载运算符“()”来模拟函数形式的类、结构体。
直接上例子:
1、认识仿函数
class OperatorClass {
public:
void operator()() {
cout << “仿函数(空谓词)” << endl;
}
void operator()(int a) {<br /> cout << "仿函数(一元谓词)" << a << endl;<br /> }
void operator()(int a, int b) {<br /> cout << "仿函数(二元谓词)" << a << "," << b << endl;<br /> }
void operator()(int a, int b, int c) {<br /> cout << "仿函数(三元谓词)" << a << "," << b << c << endl;<br /> }
void operator()(int a, int b, int c, int d) {<br /> cout << "仿函数(四元谓词)" << a << "," << b << c << "," << d << endl;<br /> }
void generalFunction() {<br /> cout << "普通函数" << endl;<br /> }<br />};<br />struct OperatorStruct {<br /> void operator()() {<br /> cout << "struct仿函数(空谓词)" << endl;<br /> }
void operator()(int a) {<br /> cout << "struct仿函数(一元谓词)" << a << endl;<br /> }
void operator()(int a, int b) {<br /> cout << "struct仿函数(二元谓词)" << a << "," << b << endl;<br /> }
void operator()(int a, int b, int c) {<br /> cout << "struct仿函数(三元谓词)" << a << "," << b << c << endl;<br /> }
void operator()(int a, int b, int c, int d) {<br /> cout << "struct仿函数(四元谓词)" << a << "," << b << c << "," << d << endl;<br /> }<br />};<br />int main() {<br /> OperatorClass operatorClass;<br /> operatorClass();<br /> operatorClass(1);<br /> operatorClass(1, 2);<br /> <br /> struct OperatorStruct operatorStruct;<br /> operatorStruct();<br /> operatorStruct(10);<br /> operatorStruct(10, 11, 12, 14);<br /> return 0;<br />}
2、for_each做遍历
class Foreach {
public:
int count = 0;
void operator()(int value) {
cout << “仿函数实现:” << value << endl;
count++;
}
void showCount() {
cout << “循环次数:” << count << endl;
}
};
//普通函数实现回调功能
void _f(int value) {
cout << “普通函数实现:” << value << endl;
}
int main() {
set
setVar.insert(50);
setVar.insert(10);
setVar.insert(20);
setVar.insert(30);
setVar.insert(40);
//普通的循环遍历
for (set
cout << it << endl;
}
cout << “for_each” << endl;
//通过函数回调进行for_each遍历,根据源码可知道遍历的回调方法需要一个参数 first 这里是int
for_each(setVar.begin(), setVar.end(), _f);
Foreach foreach;
//通过仿函数进行for_each遍历,根据源码知道传入的对象属于拷贝,使用完之后会返回拷贝之后的对象
foreach = for_each(setVar.begin(), setVar.end(), foreach);
//根据源码可知,for_each最后会将传入的对象返回,记录遍历次数
foreach.showCount();
return 0;
}
3、自定义比较函数
class Compare {
public:
//比较函数注意参数需要const 方法也需要 const 根据源码而来
bool operator()(const Test &t1, const Test &t2) const {
return t1.value < t2.value;
}
//for_each循环map时的回调,*map::iterator的结果是pair对象<br /> //根据 typeid(*it).name来测试得到该类型<br /> void operator()(pair<Test, int> itemPair) {<br /> cout << "name:" << itemPair.first.name << " age:" << itemPair.first.value << " Value:" << itemPair.second<br /> << endl;<br /> }<br />};
int main() {
//默认比较函数为 less更小的在前,greater更大的在前
map
maps[Test(“双姐姐”, 31)] = 82;
maps[Test(“黄家宁”, 2)] = 100;
maps[Test(“野锅锅”, 30)] = 80;
Compare compare;
for_each(maps.begin(), maps.end(), compare);
return 0;
}