微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C 11 – 绑定排序功能

我想保存自己一些打字,因此定义如下:
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(),[](...){ ... });

原文地址:https://www.jb51.cc/c/112386.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐