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

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 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64