Windrunner7 2016-05-27 03:27 采纳率: 0%
浏览 3374
已采纳

C++怎么在类中使用sort,比较函数是非静态成员函数

简易代码如下

#include <iostream>
#include <algorithm>

using namespace std;

struct B {
    int x = 0;
};

class A {
public:
    A() {
        b[0].x = 0;
        b[1].x = 1;
        b[2].x = 2;
        b[3].x = 3;
        b[4].x = 4;
    }

    void test() {
        sort(b, b + 5, cmp);    // 这行报错
        for (int i = 0; i < 5; ++i) {
            cout << b[i].x << endl;
        }
    }

    bool cmp(B b1, B b2) {
        return c[b1.x] > c[b2.x];
    }

private:
    B b[5];
    int c[5] = {11, 22, 33, 44, 55};
};

int main() {
    A testa;
    testa.test();
    system("pause");
    return 0;
}

非静态成员函数参数会自带this,怎么办?

  • 写回答

2条回答 默认 最新

  • Valtava 2016-05-27 15:14
    关注

    用std::bind

     #include <iostream>
    #include <algorithm>
    #include <functional>
    
    using namespace std;
    using std::placeholders::_1;
    using std::placeholders::_2;
    
    struct B {
        int x = 0;
    };
    
    class A {
    public:
        A() {
            b[0].x = 0;
            b[1].x = 1;
            b[2].x = 2;
            b[3].x = 3;
            b[4].x = 4;
        }
    
        void test() {
            auto bound_cmp=bind(&A::cmp, this, _1, _2);
            sort(b, b + 5, bound_cmp);
            for (int i = 0; i < 5; ++i) {
                cout << b[i].x << endl;
            }
        }
    
        bool cmp(B b1, B b2) {
            return c[b1.x] > c[b2.x];
        }
    
    private:
        B b[5];
        int c[5] = {11, 22, 33, 44, 55};
    };
    
    int main() {
        A testa;
        testa.test();
            system("pause");
        return 0;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘