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 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)