C++ 11 - 绑定排序函数

ryy*_*yst 10 c++ 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
Run Code Online (Sandbox Code Playgroud)

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

使用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, vec.begin(), vec.end(), [] (pair<int, int> const &a, pair<int, int> const &b) {
            return a.first < b.first;
        });

    vecsort();

}
Run Code Online (Sandbox Code Playgroud)

错误:

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

Die*_*ühl 12

问题是它std::sort不是一个功能对象.它是一个功能模板.处理该问题的最简单方法是创建一个简单的包装器对象:

struct sorter {
    template <typename RndIt, typename Cmp>
    void operator()(RndIt begin, RndIt end, Cmp cmp) {
        std::sort(begin, end, cmp);
    }
};
Run Code Online (Sandbox Code Playgroud)

现在你可以使用了

std::bind(sorter(), vec.begin(), vec.end(), [](...){ ... });
Run Code Online (Sandbox Code Playgroud)


Jam*_*mes 7

其他人已经提到它为什么不编译,但这个替代解决方案是否适合您?这使用另一个lambda而不是bind来创建std :: function.

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

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 = [&vec] {
        sort(vec.begin(), vec.end(), 
        [] (pair<int, int> const &a, pair<int, int> const &b) {
            return a.first < b.first;
        });
     };

    // vecsort will work as long as vec is in scope.
    // vecsort will modify the original vector.
    vecsort();
    for (auto i : vec) {
        std::cout << '(' << i.first << ", " << i.second << ") ";
    }
    std::cout << endl;

    vec.push_back(make_pair(-42, 0));
    vecsort();
    for (auto i : vec) {
        std::cout << '(' << i.first << ", " << i.second << ") ";
    }
    std::cout << endl;
}
Run Code Online (Sandbox Code Playgroud)

输出:

(1, 0) (2, 0) (3, 0) (4, 0) (5, 0) (6, 0) (7, 0) (8, 0) (9, 0) (10, 0)
(-42, 0) (1, 0) (2, 0) (3, 0) (4, 0) (5, 0) (6, 0) (7, 0) (8, 0) (9, 0) (10, 0)
Run Code Online (Sandbox Code Playgroud)

看到它在这里运行:http: //ideone.com/W2YQKW