C ++包含类的排序列表

时间:2013-01-13 13:50:10

标签: c++ list sorting

我有一个小问题。我目前正在为锦标赛处理编写一个代码,并且我想出了一种方法,即在内存中保持团队秩序的最佳方式将是一个列表。 现在,我正在尝试对包含点记录的Team类进行排序。 这是类声明:

#include "player.h"
#include <string>

class Team {
Player** Gracz;
std::string Name;
int TP, STP;
int Total;

public:
Team();
Team(Player* gracz1, Player* gracz2, Player* gracz3, Player* gracz4, Player*     gracz5, Player* gracz6, std::string name);
~Team();

void SetTeam();
void SetTeam(Player gracz1, Player gracz2, Player gracz3, Player gracz4, Player gracz5, Player gracz6, std::string name);
void SetTP(int tp);
void SetSTP(int stp);

std::string GetTeam();
int GetTotal();
int GetTP();
int GetSTP();

bool operator<(Team& team);
bool operator>(Team& team);

void PrintTeam();
};

这是程序代码:

#include <iostream>
#include "player.h"
#include "team.h"
#include <list>
#include <string>

using namespace std;

int main(int argc, char *argv[]) {
Player *p;
Team *t1, *t2, *t3, *t4;
list<Team> x;
list<Team>::iterator it;

p=new Player("a","a","a");

t1=new Team(p,p,p,p,p,p,"A");
t2=new Team(p,p,p,p,p,p,"B");
t3=new Team(p,p,p,p,p,p,"C");
t4=new Team(p,p,p,p,p,p,"D");

x.push_back(*t1);
x.push_back(*t2);
x.push_back(*t3);
x.push_back(*t4);

cout<<"Turniej: "<<endl;
for(it=x.begin();it!=x.end();++it)
    cout<<" "<<(*it).GetTeam();
cout<<endl;

t1->SetTP(15);
t2->SetTP(4);
t3->SetTP(8);
t4->SetTP(8);
t3->SetSTP(15);
t4->SetSTP(65);

x.sort(); 

cout<<"Turniej: "<<endl;
for(it=x.begin();it!=x.end();++it)
    cout<<" "<<(*it).GetTeam();
cout<<endl;

return 0;
}

所以我想首先按TP排序列表,然后按STP排序,并将其包含在重载运算符&lt;的声明中。当我打印列表时,我在排序之前得到A,B,C,D,在排序之后得到相同的,而不是A,D,C,B之后。哪里是我的错?

感谢您的帮助。

1 个答案:

答案 0 :(得分:5)

此处复制对象,并将其副本推送到容器中:

x.push_back(*t1);
/* the same for others */

在这里修改原始对象,但容器中的副本保持不变:

t1->SetTP(15);