c++内建函数对象

概念:
STL内建了一些函数对象
分类:
算术仿函数
关系仿函数

逻辑仿函数
用法:
这些仿函数所产生的对象,用法和一般函数完全相同
使用内建函数对象,需要引入头文件 #include<functional>

 

算术仿函数
功能描述:
实现四则运算
其中negate是一元运算,其他都是二元运算
仿函数原型:
template<class T> T plus<T> //加法仿函数
template<class T> T minus<T> //减法仿函数
template<class T> T multiplies<T> //乘法仿函数
template<class T> T divides<T> //除法仿函数
template<class T> T modulus<T> //取模仿函数
template<class T> T negate<T> //取反仿函数

例如plus的stl源码和具体实现,源码中使用了template的方法来进行

//二元函数的参数和返回值类型,通常被继承
template <class Arg1, class Arg2, class Result>
struct binary_function {
    typedef Arg1 first_argument_type;
    typedef Arg2 second_argument_type;
    typedef Result result_type;
}; 

template <class T>
struct plus : public binary_function<T, T, T> {
    T operator()(const T& x, const T& y) const { return x + y; }
};

  negate<int> n;
  cout << n(50) <<endl;
  plus<int> p;
  cout << p(10,20) <<endl;
 

关系仿函数

功能描述:
实现关系对比
仿函数原型:
template<class T> bool equal_to<T> //等于
template<class T> bool not_equal_to<T> //不等于
template<class T> bool greater<T> //大于
template<class T> bool greater_equal<T> //大于等于
template<class T> bool less<T> //小于
template<class T> bool less_equal<T> //小于等于

stl源码

template <class T>
struct greater : public binary_function<T, T, bool> {
    bool operator()(const T& x, const T& y) const { return x > y; }
};//默认的从大到小排列

sort(v.begin(),v.end(),greater<int>());

 

 

逻辑仿函数

功能描述:
实现逻辑运算
函数原型:
template<class T> bool logical_and<T> //逻辑与
template<class T> bool logical_or<T> //逻辑或
template<class T> bool logical_not<T> //逻辑非

stl源码

template <class T>
struct logical_and : public binary_function<T, T, bool> {
    bool operator()(const T& x, const T& y) const { return x && y; }
};

  logical_and<int> l;
  cout <<  l(0,0) <<endl;

 

 

posted @   纸包鱼  阅读(30)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
· Manus的开源复刻OpenManus初探
点击右上角即可分享
微信分享提示