如何对类成员向量进行排序?

时间:2019-06-17 18:19:01

标签: c++ sorting vector

我正在用一个代码对每个元素的键进行排序,并且正在使用STL函数sort。但是,我需要的关键函数必须是类的非静态函数,并且编译器拒绝接受该函数。任何建议都很赞赏。

#include <bits/stdc++.h>

class Class {
    public:
        Class (int i): my_int(i) {}
        int f (int x) { return x % my_int; }
        bool key (int i1, int i2) { return f(i1) < f(i2); }
        void sort_v () { std::sort(v.begin(), v.end(), this->key) }
    private:
        std::vector<int> v = {4,6,3,2};
        int my_int;
};

int main() {
    Class c(3);
    c.sort_v();
    return 0;
}

注意:朋友函数无法轻松实现,因为key(int,int)的参数是自动传递的,并且由于f不是静态的,所以我们无法传递“此类”数据。

2 个答案:

答案 0 :(得分:3)

只需使用lambda:

void sort_v () {
    std::sort(v.begin(), v.end(), [this](auto a, auto b) { return key(a, b); });
}

答案 1 :(得分:-1)

您可以使用std::bind

void sort_v () { 
    using std::placeholders;
    std::sort(v.begin(), v.end(), std::bind( &Class:key, this, _1, _2 ) ); 
}

或使用lambda:

void sort_v () { 
    std::sort(v.begin(), v.end(), [this]( int x, int y ) { return key( x, y ); ); 
}

使您的方法有效。