首页 > 解决方案 > C ++对结构向量进行排序

问题描述

我是 C++ 新手,正在尝试根据另一个向量中的值对向量进行排序。我试图通过创建结构向量并使用 STL 对结构向量进行排序来实现这一点。这些结构有 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 字段定义的。

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

标签: c++sortingvectorstructstl

解决方案


你需要超载operator<而不是operator>

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

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

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

编辑(再次,由于问题太长,有两个问题):

向量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——我不会告诉你所有这些。请找到!


推荐阅读