zoukankan      html  css  js  c++  java
  • Sword STL仿函数示例

    一元函数 unary_function
    1.有返回值.
    2.只有一个参数.
    template <class Arg, class Result>
      struct unary_function {
        typedef Arg argument_type;
        typedef Result result_type;
      };
      
    unary_function可以作为一个一元函数对象的基类,它只定义了参数和返回值的类型,本身并不重载()操作符,这个任务应该交由派生类去完成。
    
     
    二元函数 binary_function
    1.有返回值.
    2.两个参数.
    
    binary_function可以作为一个二元函数对象的基类,它只定义了参数和返回值的类型,本身并不重载()操作符,这个任务应该交由派生类去完成。
    
    template <class Arg1, class Arg2, class Result>
      struct binary_function {
        typedef Arg1 first_argument_type;
        typedef Arg2 second_argument_type;
        typedef Result result_type;
    };
    /* 仿函数 */
    #include <iostream>
    #include <map>
    #include <vector>
    #include <algorithm>  //std::sort
    #include <functional> //binary_function类和unary_function类
    
    using namespace std;
    
    struct STComp:public binary_function<int,int,bool>
    {
        inline bool operator()(int x, int y)
        {
            return x > y;
        }
    };
    
    struct STPrint :public unary_function<int, bool>
    {
        inline void operator()(int x)
        {
            cout << x << endl;
        }
    };
    
    void test()
    {
        vector<int> v1 = { 1,2,3,4,5,6,7,8 };
        //仿函数的应用
        sort(v1.begin(), v1.end(), STComp());
        for_each(v1.begin(), v1.end(), STPrint());
    }
    
    int main()
    {
        test();
        getchar();
        return 0;
    }
    为什么函数对象的性能优于函数指针
    在调用带有函数指针的函数时,编译器产生一个间接函数调用——通过指针调用。 大部分编译器不会试图去内联通过函数指针调用的函数
    (甚至函数已经声明为inline而且这个优化看起来很直接)。但是函数对象的成员函数可以声明为内联方法
  • 相关阅读:
    20180827 360笔试客观题
    20180821 hikvision笔试
    20180820 美团一面
    20180811 网易
    20180811 多益网络
    20180810 多益网络模拟笔试
    hbase --知识点总结
    flume知识点总结
    oracle --hint总结
    查看oracle的执行计划
  • 原文地址:https://www.cnblogs.com/zhanggaofeng/p/9880443.html
Copyright © 2011-2022 走看看