C++对结构向量进行排序
C++ sorting a vector of structs
我是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::sort
并rend()
(反向(迭代器:
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
函子更自然。
- 计算排序向量的向量中唯一值的计数
- 查找两个排序向量中共有的元素
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- 如何从C++的对的排序向量中获取有关给定值的相应对
- 对象接收堆栈溢出异常 c++ 的排序向量
- "x"的所有元素都存在于"y"(排序向量)中吗?
- 指向指针排序向量的指针向量的 C++ 向量
- 未排序向量上的lower_bound/upper_bound
- 智能指针的排序向量:神秘崩溃
- 按类型排序向量并按类型或派生类型搜索
- 如何在不使用标准算法的情况下在排序向量中添加 c 元素?
- C++排序向量<double>与在<Object>双成员变量上键控的向量
- 字符串指针的排序向量
- 具有前导数字的字符串的排序向量
- 保证重新排序向量
- 结构解释的C 排序向量
- 更新排序向量的一个条目
- 通过在排序向量上使用二叉搜索来定位未排序向量中的元素
- 排序向量上 std::find_if 和 std::bind2nd 的替代品
- 使用QuickSort算法以降序排序向量