C++有关std::sort和std::bind那些事

背景

使用sort函数经常需要自定义排序方法与权重,不想overload比较方法就需要向sort中传入第三个compare参数。

实现

bind

对于比较复杂的可以使用std::bind构建一个新的函数对象,固化某些参数并使用placeholder接收外部参数

vector<int> v = { 1, 8, 7, 4, 3, 6, 2, 5 };
PrintVector(v);
auto greater_binded = bind(greater<int>(), placeholders::_1, placeholders::_2);
sort(v.begin(), v.end(), greater_binded);

注意,如果在class中使用了调用了非静态成员函数进行bind,则需要显式传入this指针。

lambda

对于比较简单的比较则更推荐使用lambda表达式构建匿名函数,例如

std::sort(s.begin(), s.end(), [](int a, int b) {
        return a > b;
    });

参考

c++ - usage of this pointer in std::bind - Stack Overflow
bind - C++ Reference

原文地址:https://www.cnblogs.com/azureology/p/15602344.html