我正在尝试使用 stable_sort 对指针 vector 进行排序
某个类(class)。我有这样的代码:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class B
{
public :
B(int y, int j) {x = y, r = j;};
void getVal() {cout << x << endl; };
int x;
int r;
};
bool compareB(B* b1, B* b2)
{
return b1->getVal() < b2->getVal();
}
int main()
{
B b1(3, 4), b2(-5, 7), b3(12, 111);
vector<B*> myVec;
myVec.push_back(&b1);
myVec.push_back(&b2);
myVec.push_back(&b3);
std::stable_sort(myVec.begin(), myVec.end(), compareB);
for (size_t size = 0; size < myVec.size(); ++size)
{
myVec[size]->getVal();
}
return 0;
}
然而,我在编译时遇到了一个愚蠢的错误:
“错误:'void' 和 'void' 类型的无效操作数到二进制 'operator<' 返回 b1->getVal() < b2->getVal();"
有人可以帮助我吗?
最佳答案
问题在于
void getVal() {cout << x << endl; };
它返回 void
而不是一些值(value)。
当你在 return b1->getVal() < b2->getVal();
中使用它时归结为 return void < void;
这不会编译。
你应该可以把它改成
int getVal() { return x; };
关于c++ - C++ 中的稳定排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32360266/