stable_sort 在 C++ 中
stable_sort in C++
我正在尝试使用 stable_sort 对指针向量进行排序
到某个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<'
return b1->getVal() < b2->getVal();"
有人可以帮助我吗?
问题在于
void getVal() {cout << x << endl; };
它 returns void
而不是一些值。
当您在 return b1->getVal() < b2->getVal();
中使用它时,它归结为 return void < void;
无法编译。
您应该可以将其更改为
int getVal() { return x; };
我正在尝试使用 stable_sort 对指针向量进行排序
到某个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<' return b1->getVal() < b2->getVal();"
有人可以帮助我吗?
问题在于
void getVal() {cout << x << endl; };
它 returns void
而不是一些值。
当您在 return b1->getVal() < b2->getVal();
中使用它时,它归结为 return void < void;
无法编译。
您应该可以将其更改为
int getVal() { return x; };