C++ 不同对象的向量排序
我试图给出一个排序函数,之前,在一些帮助下,可以根据存储在对象向量中的变量进行排序 两点是我的目标C++ 不同对象的向量排序,c++,sorting,object,vector,C++,Sorting,Object,Vector,我试图给出一个排序函数,之前,在一些帮助下,可以根据存储在对象向量中的变量进行排序 两点是我的目标 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 fun
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);
}
bool比较(常量两点D&a,常量两点D&b)
{
返回a.getcivIndex()>b.getcivIndex();
//从高到低排序
}
//要进行排序,我只需在函数中调用它
无效排序(向量和向量)
{
排序(Vector.begin()、Vector.end()、比较);
}
基于此,我尝试重新创建它
ShapeWod现在是我的对象,也是父类。
我有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
}
}
bool compareAscend(ShapeTwoD&a、ShapeTwoD&b)
{
返回b.getArea()>a.getArea();
}
布尔比较搜索(ShapeTwoD&a、ShapeTwoD&b)
{
返回a.getArea()>b.getArea();
}
//如果我只编译这个,编译器就可以了
无效排序(向量和向量)
{
字符串选择;
cout当您尝试对包含shapewod*
s的向量进行排序时,比较函数也必须与shapewod*
一起使用,而不是shapewod&
或shapewod const&
改变
bool compareAscend(ShapeTwoD& a, ShapeTwoD& b)
{
return b.getArea() > a.getArea();
}
到
类似地更改compareDescend
。您的问题是?为基类创建一个虚拟比较函数,并在必要时为所有其他对象重新实现它。@NathanOliver我已经更新了question@Nidhoegger怎么做?我在基类中创建了虚拟排序函数?@Nidhoegger和我只想排序基于存储在向量中的区域,这就是为什么我在两个向量之间使用getArea()
,并对它们进行排序和存储。谢谢,即使在阅读了指针教程之后,我也不太清楚*
和&
是什么
bool compareAscend(ShapeTwoD* a, ShapeTwoD* b)
{
return b->getArea() > a->getArea();
}