其中包含不同对象的矢量排序
Vector sorting with different objects in it
我试图在以前的一些帮助下提出一个排序函数,设法做了一种基于存储在对象向量的变量上的类别。
PointTwod是我的对象。
bool compare(const PointTwoD& a, const PointTwoD& b)
{
return a.getcivIndex() > b.getcivIndex();
//sort from high to low
}
//to do the sort, i will just have to call it in my function
void Sort(vector<PointTwoD>& Vector)
{
sort(Vector.begin(), Vector.end(), compare);
}
以此为基础,我试图重新创建它。
shapetwod是我的对象,也是父级。我有3个用于多态性的子类,我将子类对象存储到向量中。
bool compareAscend(ShapeTwoD& a, ShapeTwoD& b)
{
return b.getArea() > a.getArea();
}
bool compareDescend(ShapeTwoD& a, ShapeTwoD& b)
{
return a.getArea() > b.getArea();
}
//if i only compile this, the compiler is fine with this
void Sort(vector<ShapeTwoD*>& Vector)
{
string choice;
cout << "nna)tSort by area (ascending)" << endl;
cout << "b)tSort by area (descending)" << endl;
cout << "c)tSort by special type and area" << endl;
cout << "tPlease select sort option (‘q’ to go main menu): ";
cin >> choice;
transform(choice.begin(), choice.end(), choice.begin(), ::tolower);
if (choice == "a")
{
sort(Vector.begin(), Vector.end(), compareAscend);
//these lines are giving the error
}
else if (choice == "b")
{
sort(Vector.begin(), Vector.end(), compareDescend);
//these lines are giving the error
}
}
但是,当我尝试编译时,编译器会给我带来很多错误,我不明白。
当您尝试对包含ShapeTwoD*
s的vector
进行分类时,比较函数也必须使用ShapeTwoD*
,而不是ShapeTwoD&
或ShapeTwoD const&
。
更改
bool compareAscend(ShapeTwoD& a, ShapeTwoD& b)
{
return b.getArea() > a.getArea();
}
to
bool compareAscend(ShapeTwoD* a, ShapeTwoD* b)
{
return b->getArea() > a->getArea();
}
类似地更改compareDescend
。
相关文章:
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 对象接收堆栈溢出异常 c++ 的排序向量
- 如何使用 STL 排序对具有模板专用化的自定义类对象进行排序?
- 排序谓词没有传递对索引对象的引用?
- 使用指针指向对象C++对向量进行排序
- 按类成员的顺序对包含类对象的C++向量进行排序
- 无法使用接口类型对priority_queue中的对象进行排序<T>
- 基于不同字段的对象向量的排序功能
- 基于3个对象的自定义排序
- 尝试使用比较运算符对对象向量进行排序
- C++排序的对象集
- 从文件中读取并将其内容放入对象数组中,然后对它们进行排序
- q排序类对象的列表
- std::atexit 从全局对象的构造函数调用时的排序
- 尝试对对象数组进行排序时程序终止
- std::排序为排序自定义对象时出现的向量引发错误
- 使用sort()算法C 排序对象列表
- 使用std::sort与自定义排序对象和数据类型模板-寻找正确的语法
- 快速方法部分排序对象
- 如何在动态内存中排序对象列表,在c++中使用泛型向量