【发布时间】:2015-05-14 17:37:08
【问题描述】:
我正在尝试提供一个排序功能,之前在一些帮助下,设法进行排序,该排序基于存储在对象向量中的变量。
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
}
}
但是当我尝试编译时,编译器会给我大量错误,我不明白。
【问题讨论】:
-
你的问题是?
-
为基类创建一个虚拟比较函数,并在必要时为所有其他对象重新实现它。
-
@NathanOliver 我已经更新了问题
-
@Nidhoegger 我该怎么做?我在基类中创建虚拟排序函数?
-
@Nidhoegger 我只想根据存储在向量中的区域进行排序,这就是为什么我在两个向量之间使用
getArea()并将它们排序并存储回。 >