C++按私有(private)变量对数组进行排序

标签 c++

我有这门课

Class VehicleTwoD
{
private:
doubleArea;
}

所以我想按doubleArea排序;

在我的 main.cpp 中

我得到了

int main()
{
VehicleTwoD *vehicletwod[100];
sort(vehicletwod[0], vehicletwod[vehicleCounter]);

for (int i=0;i<vehicleCounter;vehicleCounter++)
    {
cout << "Vehicle " << i << end;
cout << vehicletwod[i]->toDisplay() << endl;
    }
}

Below is my operator overload at Vehicle.h


bool VehicleTwoD::operator<(const VehicleTwoD& rhs) const
{
return area > rhs.area;
}

当我尝试运行该程序时,出现运行时错误 - 分段核心转储错误。

假设我的 Vehicle Counter 没有错误,并且当我尝试运行 toDisplay 时我的 Vehicletwod 至少有 2 个对象,实际上出了什么问题..

更新:

我之所以这样做,是因为我从这里的专家那里收到了宝贵的反馈意见。

在 main.cpp

int main()
{
VehicleTwoD *vehicletwod[100];

for(int i=0;i<100;i++)
{
vehicletwod[i] = new VehicleTWoD();
}

//some computation then I go to sort..

sort(&vehicletwod[0],&vehicletwod[vehicleCounter]);

for(int i=0;i<vehicleCounter;i++)
{
cout << vehicletwod->toDisplay() << endl;
}

}

输出保持不变,没有任何排序..我不知道为什么..

这是我在 VehicleTwoD.h 中做的 bool 运算符

VehicleTwoD.h

public:
bool operator<(const VehicleTwoD&) const;

VehicleTwoD.cpp

bool VehicleTwoD::operator<(const VehicleTwoD& rhs) const
{
return area > rhs.area;
}

什么都没有排序..我希望至少它按降序或升序排序..

我想知道是否有一种方法可以将我的 VehicleTwoD 数组分配到一个 vector 调用 sortVector 中,因为在按升序排序后,我还想按降序排序。

所以 vector 中的反向函数将很好地解决它。

有什么建议吗?感谢这里所有乐于助人和善良的专家!!

最佳答案

VehicleTwoD *vehicletwod[100];

这只是创建了一个指向无效内存位置的引用数组。

您需要一个循环或其他方法来分配 100 个有效引用。示例:

for(int i=0;i < 100;i++)
{
  vehicletwod[i] = new VehicleTwoD() ;
}

而且你必须记得释放那些内存。

关于C++按私有(private)变量对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13154838/

相关文章:

c++ - 继承类型定义?

c++ - STEAM:无法使用 Steam 初始化游戏服务器 - 警告无法托管

c# - 为什么 STL 中的 set_intersection 这么慢?

C++ 单头文件结构

c++ - 观看来自可执行文件的指令?

c++ - 这个模板定义在 C++ 中意味着什么?

c++ - 在类字段上使用预处理器 #ifdef

c++ - 线性方程组与opencv,c++

c++ - Shmem vs tmpfs vs mmap

c++ - QWidget 的一个简单子(monad)类不能用作 QWidget