c++ - 对象的排序 vector 不起作用

标签 c++

本站第一个问题,我想按获得的积分排序,球队排名,有错误但是做空不行。 我需要你的帮助来解决这个问题

团队.h

class Team
{
private:
    std::string t_name;
    int t_rank;

public:
    int t_points;
    Team(std::string name);
    ~Team();
    void win();
    void show(std::ostream &Flux)const;
};
std::ostream& operator<<(std::ostream &Flux, Team const &B);
bool operator<(Team const& A,Team const& B);

团队.cpp

Team::Team(string name): t_name(name), t_points(0) {}

void Team::win()
{
    t_points+=3;
}

void Team::show(std::ostream &Flux)const
{
    Flux << t_name;
}

std::ostream& operator<<(std::ostream &Flux, Team const &B)
{
    B.show(Flux);
    return Flux;
}

bool operator<(Team const& A,Team const& B){
    return A.t_points < B.t_points;
}

主要.cpp

int main()
{
    vector <Team*> Schedule;

    Schedule.push_back(new Team("Celtics")); //0
    Schedule.push_back(new Team("Nets"));//1
    Schedule.push_back(new Team("Bulls"));//2

    Schedule[1]->win();
    Schedule[1]->win();
    Schedule[2]->win();

    std::sort(Schedule.begin(), Schedule.end());
    for(int i(0); i<Schedule.size(); i++)
    {
        cout << i << " - " << *Schedule[i] << endl;
    }

    return 0;
}

我已经编辑了我的文件以添加您提供的信息,但仍然无法解决我的问题,所以我重新发布所有内容并等待更多帮助

最佳答案

vector<Team*>存储一个你需要重载 operator<(const Team*, const Team*) operator 的指针像这样:

bool operator<(const Team* left, const Team* right) {
    return left->whatever < right->whatever;
}

关于c++ - 对象的排序 vector 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46119957/

相关文章:

c++ - Installshield,安装应用程序后,系统会提示用户安装程序

c++ - 模板类型名实例化错误

c++ - 分段故障运行 boost 示例

c++ - 包括 .cpp 文件

c++ - 使用符号位翻转和加法进行浮点减法

使用 std::move(nullptr) 的 unique_ptr 的 operator= C++ 错误

c++ - 为什么在作为值返回时在类内部定义结构需要范围解析?

c++ - 将像素数组保存到 jpeg 图像文件 C++

c++ - 在 QT 中向小部件添加彩色边框的最佳方法是什么

c++ - Qt-Signal 未在虚拟机中连接