【问题标题】:Vector sorting with different objects in it带有不同对象的向量排序
【发布时间】: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() 并将它们排序并存储回。 >

标签: c++ sorting object vector


【解决方案1】:

当您尝试对包含ShapeTwoD*s 的vector 进行排序时,比较函数也必须与ShapeTwoD* 一起使用,而不是ShapeTwoD&amp;ShapeTwoD const&amp;

改变

bool compareAscend(ShapeTwoD& a, ShapeTwoD& b)
{ 
    return b.getArea() > a.getArea();       
}

bool compareAscend(ShapeTwoD* a, ShapeTwoD* b)
{ 
    return b->getArea() > a->getArea();       
}

类似地更改compareDescend

【讨论】:

  • 谢谢,即使在阅读了指针教程之后,我也不太明白 *&amp; 是什么
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-08
  • 2021-02-06
  • 1970-01-01
  • 2014-12-29
  • 1970-01-01
  • 2020-12-12
  • 1970-01-01
相关资源
最近更新 更多