Set容器排序

最近项目在进行实时排序时需要有个算法能够快速的进行排序,进行一番测试及考量。现采用set容器,然后存放结构体的方式。

结构体如下所示:

 1 struct MatchData
 2 {
 3     uint32 m_score;
 4     int64 m_userid;
 5     uint32 m_medal;
 6     string m_name;
 7 
 8     MatchData()
 9     {
10 
11         this->m_score = 0;
12         this->m_userid = 0;
13         this->m_medal = 0;
14         this->m_name = "";
15     }
16 
17     MatchData(uint32 score,int64 userid,uint32 medal,string strName)
18     {
19 
20         this->m_score = score;
21         this->m_userid = userid;
22         this->m_medal = medal;
23         this->m_name = strName;
24     }
25 
26     bool operator<(const struct MatchData & right)const   //重载<运算符
27     {
28         if(this->m_userid == right.m_userid)     //根据userid去重
29             return false;
30         else
31         {
32             if(this->m_score != right.m_score)
33             {
34                 return this->m_score > right.m_score;      //降序
35             }
36             else
37             {
38                 if ( this->m_medal != right.m_medal )
39                 {
40                     return this->m_medal > right.m_medal;
41                 }
42                 else
43                 {
44                     return this->m_userid > right.m_userid;
45                 } 
46             }
47         }
48     }
49 };
View Code

 

只需要将需要的数据组成新的结构体然后插入到set容器中,就可以自动进行排序,效率方便还是可以的。在Debug模式下,排序10000人,所花时间在400毫秒左右。生成release后运行,效率将会再次提升。

set setMatchRank;//排行榜
MatchData temp;
temp.m_score = 100;
temp.m_userid = 1;
temp.m_medal = 10
temp.m_name = “test”;
setMatchRank.insert(temp);
View Code

 

转载于:https://www.cnblogs.com/itevol/p/7079827.html

你可能感兴趣的