作者LPH66 ((short)(-15074))
看板Programming
标题Re: STL sort
时间Mon Aug 3 20:04:58 2009
※ 引述《sorryChen (陈扬和)》之铭言:
: 如果我有两个分开的array 纪录 ex: 人名和对应的score
: ex:
: int name[3] = {"a", "b", "c"};
: int score[3] = {3, 2, 1}
: 现在想用stl sort成 依照score来排序
: 这样要怎麽用? 要写个自己的swap 然後怎麽丢到sort中呢?
: → shik:可以再开一个阵列存编号 124.8.3.192 08/01 22:15
这个解法应该算很接近你的需求了
例如:
char name[4][10] = {"Jessica","George","Battler","Maria"};
//最近刚跑完海猫..XD
int score[4] = {70,100,60,80};
bool compare(const int a, const int b)
{
return score[a]<score[b];
}
//in some function
int ptr[4];
for(int i=0; i<4; i++) ptr[i]=i;
sort(ptr,ptr+4,compare);
for(int i=0; i<4; i++)
{
cout << name[ptr[i]] << '\t' << score[ptr[i]] << endl;
}
如果资料不在 global 时也可以写 functor:
struct compare
{
int *score;
compare(int *s):score(s) {}
bool operator () (const int a, const int b) const
{
return score[a]<score[b];
}
};
//in some function
char name[4][10] = {"Jessica","George","Battler","Maria"};
int score[4] = {70,100,60,80};
int ptr[4];
for(int i=0; i<4; i++) ptr[i]=i;
sort(ptr,ptr+4,compare(score));
for(int i=0; i<4; i++)
{
cout << name[ptr[i]] << '\t' << score[ptr[i]] << endl;
}
不过个人还是会习惯把要一起排的资料包成 struct
一来结构上就是在一起 二来直接丢给sort就会真的排好
--
"LPH" is for "Let Program Heal us"....
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.112.250.80
1F:推 sorryChen:非常感谢 207.151.231.16 08/04 06:25
2F:→ sorryChen:我後来也是包成struct排 但要两倍空间 207.151.231.16 08/04 06:26
3F:推 yoco315:喂.. 为什麽要两倍空间... @@118.160.112.214 08/04 21:37
4F:→ sorryChen:因为原本的array还是得在阿 128.125.87.33 08/07 04:36