如何使用自定义比较器对数组进行排序

How can I sort an array using a custom comparator?

本文关键字:排序 数组 何使用 自定义 比较器      更新时间:2023-10-16

当我从下面的代码中调用build函数时,我会得到以下编译错误:

error C3867: 'SuffixArray::cmp': function call missing argument list; use '&SuffixArray::cmp' to create a pointer to member
error C2780: 'void std::sort(_RanIt,_RanIt)' : expects 2 arguments - 3 provided

这是我的代码:

class A{
private:
    std::string text;
    std::vector<int> array;
    bool cmp(int a, int b) {
        return std::lexicographical_compare(text.begin() + a, text.end(),
                                            text.begin() + b, text.end());
    }
    void build(const std::string &str, std::vector<int> &vec) {
        // Some vector values actions.
        std::sort(vec.begin(), vec.end(), cmp);
    }
};

这里怎么了?我使用的是Visual C++编译器。

您的比较函数A::cmpA的非静态成员。因此,它需要三个参数:除了显式声明的两个参数外,还需要一个指向A的指针来成为隐式可用的this。它还有一种不同于普通函数指针的类型:bool (A::)(int, int),当通过值传递时,它会衰减为bool (A::*)(int, int)

但是,您可以将函数std::bind()转换为一个合适的对象:

std::sort(vec.begin(), vec.end(),
          std::bind(&A::cmp, this, std::placeholders::_1, std::placeholders::_2));

@DietmarKühl的回答完美地解释了为什么您的代码没有编译。但由于C++11,您也可以使用lambda表达式,而不是定义比较函数或使其静态:

#include <vector>
#include <algorithm>
class A{
private:
    std::string text;
    std::vector<int> array;
    void build(const std::string &str, std::vector<int> &vec) {
        // Some vector values actions.
        std::sort(vec.begin(), vec.end(), [this](int a, int b) {
            return std::lexicographical_compare(text.begin() + a, text.end(),
                                                text.begin() + b, text.end());
        });
    }
};

为了能够访问lambda表达式中的类成员text,我捕获了this指针。但是,如果您想要捕捉this的替代方案,请查看此答案。