STL 仿函数

介绍

  • 仿函数和谓词一般不单独使用,都是和STL中的算法或者容器结合使用实现一些自定义的功能
  • 容器都是class template,算法都是function template。

普通类成员函数为什么不能作谓词?

因为普通成员函数有this指针这个参数,与算法的参数列表不匹配,因此静态成员函数可以用作谓词

Examples

#include <vector>
#include <map>
#include <algorithm>
#include <iostream>

using namespace std;

typedef int KEY_TYPE;
typedef int VALUE_TYPE;
typedef pair<KEY_TYPE, VALUE_TYPE> ELEM_TYPE;

// 二元谓词
bool greater_as_binary_predicate(ELEM_TYPE &left, ELEM_TYPE &right){
    return left.second > right.second;
}

// 仿函数,C++标准推荐使用这种方式, 这种方式可以兼容STL中地适配器
struct greater_as_functor{
    bool operator()(const ELEM_TYPE &left, const ELEM_TYPE &right){
        return left.second > right.second;
    }
};

class MyClass{

public:
    map<KEY_TYPE, VALUE_TYPE> _map;

    MyClass()= default;
    explicit MyClass(map<KEY_TYPE, VALUE_TYPE>& _m){ _map = _m; }

    static bool greater_as_static_member_fun(const ELEM_TYPE &left, const ELEM_TYPE &right){
        return left.second > right.second;
    }

    vector<int> topK_keys(int k = 0){
        vector<int> ans;
        ans.reserve(k);

        vector<ELEM_TYPE> _vec; _vec.resize(_map.size());
        copy(_map.begin(), _map.end(), _vec.begin());

        // 使用静态成员函数
        // sort(_vec.begin(), _vec.end(), greater_as_static_member_fun);

        // 使用定义在类外的二元谓词
        // sort(_vec.begin(), _vec.end(), greater_as_binary_predicate);

        // 使用仿函数, 仿函数本质上一个类, 所以这儿要传入一个临时对象
        sort(_vec.begin(), _vec.end(), greater_as_functor());

        for(int idx = 0; idx < k; idx++){
            ans.push_back(_map[_vec[idx].first]);
        }

        _vec.clear();
        return ans;
    }
};

int main(){

    map<KEY_TYPE, VALUE_TYPE> _m = {{1, 3}, {2, 90}, {3, 100}, {4, 50}};
    MyClass so(_m);
    auto ans = so.topK_keys(_m.size());
    for(auto& it: ans){
        cout << it << endl;
    }
    cout << endl;

    return 0;
}
posted @ 2020-04-30 15:37  lkyf  阅读(130)  评论(0)    收藏  举报