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;
}

原文链接: https://www.cnblogs.com/lkyf/p/12809190.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    STL 仿函数

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/345443

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午3:15
下一篇 2023年3月2日 上午3:15

相关推荐