其中包含不同对象的矢量排序

Vector sorting with different objects in it

本文关键字:排序 对象 包含不      更新时间:2023-10-16

我试图在以前的一些帮助下提出一个排序函数,设法做了一种基于存储在对象向量的变量上的类别。

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