简易代码如下
#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,怎么办?
用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;
}
标准库的soet不行,你需要再写一个静态函数封装下对那个成员的调用。不过因为你的cmp没有实际使用this指针,理论上你也可以通过嵌入式汇编,强行改变ebp寄存器,平衡堆栈,让sort调用不发生错误。
这个技巧你可以google下,属于偏方,不推荐。