加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C 11 – 绑定排序功能

发布时间:2020-12-16 03:11:01 所属栏目:百科 来源:网络整理
导读:我想保存自己一些打字,因此定义如下: using namespace std;vectorMyClass vec;auto vecsort = bind(sort,vec.begin(),vec.end(),[] (MyClass const a,MyClass const b) { // custom comparison function });vecsort(); // I want to use vecsort() a lot af
我想保存自己一些打字,因此定义如下:
using namespace std;

vector<MyClass> vec;

auto vecsort = bind(sort,vec.begin(),vec.end(),[] (MyClass const &a,MyClass const &b) {
        // custom comparison function
    });

vecsort(); // I want to use vecsort() a lot afterwards

由于某种原因,这不能编译 – 为什么?

使用boost不是一个选项.

最小工作实例:

#include <vector>
#include <utility>
#include <algorithm>
#include <functional>

using namespace std;

int main() {

    vector<pair<int,int>> vec;
    for (int i = 0; i < 10; i++)
        vec.push_back(make_pair(10 - i,0));

    auto vecsort = bind(sort,[] (pair<int,int> const &a,pair<int,int> const &b) {
            return a.first < b.first;
        });

    vecsort();

}

错误:

error: no matching function for call to 'bind(<unresolved overloaded function type>,std::vector<std::pair<int,int> >::iterator,main()::__lambda0)'

解决方法

问题是std :: sort不是一个函数对象.它是一个功能模板.处理问题的最简单的方法是创建一个简单的包装器对象:
struct sorter {
    template <typename RndIt,typename Cmp>
    void operator()(RndIt begin,RndIt end,Cmp cmp) {
        std::sort(begin,end,cmp);
    }
};

现在可以使用

std::bind(sorter(),[](...){ ... });

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读