我试图提出一个sort函数,之前在一些帮助下,设法根据存储在对象向量中的变量进行排序。
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 << "\n\na)\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
}
}
但是当我尝试编译时,编译器会给我一个错误的加载,我不明白。
答案 0 :(得分:2)
当您尝试对包含vector
的{{1}}进行排序时,比较功能也必须与ShapeTwoD*
一起使用,而不是ShapeTwoD*
或ShapeTwoD&
。< / p>
更改
ShapeTwoD const&
到
bool compareAscend(ShapeTwoD& a, ShapeTwoD& b)
{
return b.getArea() > a.getArea();
}
同样更改bool compareAscend(ShapeTwoD* a, ShapeTwoD* b)
{
return b->getArea() > a->getArea();
}
。