C++对结构向量进行排序

C++ sorting a vector of structs

本文关键字:排序 向量 结构 C++      更新时间:2023-10-16

我是C++新手,正在尝试根据另一个向量中的值对向量进行排序。我正在尝试通过创建结构向量并使用 STL 对 stucts 向量进行排序来实现这一点。这些结构有 2 个数据项,一个是 CustomType,另一个是 int。我希望它按 int 字段的降序排序,因此包括一个布尔运算符重载以便能够使用 STL 排序(算法(。

该结构是使用对 CustomType 向量和最初未初始化的 int 向量的引用在函数中构造的,并将它们组合成结构向量。整数的值是通过在 CustomType 向量的每个项目上调用 SomeClass (SomeFunc( 的单独成员函数和另一个u_int8_t参数来获得的(此函数本身工作正常(。

最后,我想根据排序的结构序列替换排序的 CustomType 对象。

实现文件 (.cpp( 具有以下功能:

void SomeClass::orderFunc(std::vector<CustomType>& x, std::vector<int>& y, u_int8_t param){
std::vector<CustomStruct> xy_vec;
y.assign(x.size(), 0);   
int count  = int(x.size());

for(int i=0; i != count; ++i){
y[i] = SomeFunc(x[i], param);
}
for(int i = 0; i != count; ++i){
xy_vec[i].var1 = x[i];
xy_vec[i].var2 = y[i];
}
std::sort(xy_vec.begin(), xy_vec.end()); 
for(int i = 0; i != count; ++i){
x[i] = xy_vec[i].var2;
}
}

该结构在 SomeClass 头文件中定义,如下所示:

struct CustomStruct{
CustomType var1;
int var2;
bool operator>(const CustomStruct& a) const{
return (this->var2 > a.var2);
}
};

调用此函数时,我收到以下错误:

二进制表达式的操作数无效

bool operator(((const _T1& __x, const _T1& __y( const {return __x <__y;}

我不明白为什么 bool 运算符重载无效,因为这是为结构的 int 字段定义的。

我错过了什么?任何帮助将不胜感激。此外,任何关于更优雅的方式来做到这一点的建议也会很棒。

您需要重载operator<而不是operator>

bool operator<(const CustomStruct& a) const
{
return (this->var2 < a.var2);
}

编辑:要以相反的顺序排序,您需要使用rbegin()调用std::sortrend()(反向(迭代器:

std::sort(xy_vec.rbegin(), xy_vec.rend()); 

编辑(同样,由于问题太长,有 2 个问题(:

向量xy_vec为空,需要调用resize

std::vector<CustomStruct> xy_vec;
// Resize here
xy_vec.resize(count);
for(int i = 0; i != count; ++i){
xy_vec[i].var1 = x[i];
xy_vec[i].var2 = y[i];

或者你可以打电话给push_back——我不是在告诉你这一切。请找到!

std::sort有两个主要的重载,一个没有默认使用operator <的排序谓词,另一个没有排序谓词(详细信息在这里(。

所以你可以写一些类似的东西

struct CustomStructCmp {
bool operator()(const CustomStruct& a, const CustomStruct& b) const
{   
return a.var2 > b.var2;
}   
};
std::sort(xy_vec.begin(), xy_vec.end(), CustomStructCmp());

(如果您使用的是 C++11,则可以改用 lambda(。

或者你可以写

std::sort(xy_vec.begin(), xy_vec.end(), std::greater<CustomStruct>());

但我觉得直接使用函子/lambda 比定义operator>并使用std::greater函子更自然。