🌟hello,各位读者大大们你们好呀🌟
🍭🍭系列专栏:【C++学习与应用】
✒️✒️本篇内容:比较仿函数的代码样例,比较仿函数三种不同难度的应用示例
🚢🚢作者简介:计算机海洋的新进船长一枚,请多多指教( •̀֊•́ ) ̖́-
目录
一、代码样例
比较仿函数相当于一个类对象,通常使用它的时候要求重载一个运算符 —— 括号运算符【operator()】
因为是比较仿函数,返回默认值,所以我们通常使用bool
bool operator()()
为了让仿函数使用更广泛,可将其变为模板
下面代码就实现了 x 和 y 的比较
template<class T>
class less
{
//class默认私有,所以需要加public
public:
bool operator()(const T& x, const T& y) const
{
return x < y;
}
};
template<class T>
class greater
{
public:
bool operator()(const T& x, const T& y) const
{
return x > y;
}
};
为了与库区别开来,我们通常会创造一个命名空间存放比较仿函数
#include<iostream>
using namespace std;
// 仿函数/函数对象
namespace Lin
{
template<class T>
class less
{
public:
bool operator()(const T& x, const T& y) const
{
return x < y;
}
};
template<class T>
class greater
{
public:
bool operator()(const T& x, const T& y) const
{
return x > y;
}
};
}
二、使用场景(示例)
1.简单应用
仿函数的对象可以像函数一样使

最低0.47元/天 解锁文章
7971

被折叠的 条评论
为什么被折叠?



