简体   繁体   English

对象的排序向量不起作用

[英]sort vector of object don't work

it's first question in this website, i want to order by points acquired, the team ranking, there's any error but the shorting don't work. 这是该网站上的第一个问题,我想按获得的积分,团队排名进行排序,有任何错误,但短路不起作用。 I want your help to overcome this problem 我希望你能帮助克服这个问题

Team.h Team.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);

Team.cpp Team.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;
}

main.cpp main.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;
}

I have edit my files to add the informations you gave and that still don"t responds to m problem, so i repost all and waiting for more help 我已经编辑了文件以添加您提供的信息,但仍然无法解决问题,因此我重新发布了所有信息,等待更多帮助

Since vector<Team*> stores a pointer you need to overload the operator<(const Team*, const Team*) operator like so: 由于vector<Team*>存储了一个指针,因此您需要像这样重载operator<(const Team*, const Team*) operator

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

This works perfectly fine. 这工作得很好。 But only if a_ is not private : 但仅当a_不是private

#include <algorithm>
#include <iostream>
#include <vector>

class A {
public:
  A(size_t const& a) : a_(a) {};
  ~A(){};

  //private:                                                                                                                                                    
  size_t a_;
};

bool operator<(A const& left, A const& right) {
  return left.a_ < right.a_;
}


int main() {
  std::vector<A*> v;
  v.push_back(new A(10));
  v.push_back(new A(6));
  v.push_back(new A(8));
  for(auto const& a : v) {
    std::cout << a->get() << std::endl;
  }
  std::sort(v.begin(),v.end());
  for(auto const& a : v) {
    std::cout << a->get() << std::endl;
  }
}

Implement operator< as a member and that would be solved too: 实现operator<作为成员,这也将解决:

bool operator<(A const& other) {
  return a_ < other.a_;
}

Then, a_ can be private. 然后, a_可以是私有的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM