這個代碼在這裏顯示了這樣做的方法有兩種:
的第一種方法確實使用的qsort()。在純C,但消耗多一點記憶它
struct pair {
int distance;
int index;
};
int my_pair_compare(const void *const first, const void *const second)
{
const pair* a = (const pair*)first;
const pair* b = (const pair*)second;
if (a->distance > b->distance)
return 1;
else if (a->distance < b->distance)
return -1;
else
return 0;
}
void calculate_new_order1(int week_count, float distances[], int new_order[])
{
struct pair ab[week_count];
for (int i = 0; i<week_count; ++i) {
ab[i].distance = distances[i];
ab[i].index = i;
}
qsort(ab, week_count, sizeof(*ab), my_pair_compare);
for (int i=0; i<week_count; ++i){
new_order[i] = ab[i].index;
}
}
秒將地圖中的距離(在我的示例中)保存到地圖中,然後遍歷地圖。一種C++方式。
void calculate_new_order2(int week_count, float distances[], int new_order[])
{
std::map<float,int> ooo;
for (int week=0; week<week_count; week++) {
ooo[distances[week]] = week;
}
int t = 0;
for (auto i=ooo.begin(); i!=ooo.end(); i++) {
new_order[t] = i->second;
t++;
}
}
與第二解決方案的問題是,如果你有兩個「星期」同樣的距離,這將失敗,因爲值保存到同一個地圖索引。
向我們展示您迄今爲止編寫的代碼。 – NPE 2011-04-12 09:11:38
告訴我們你什麼時候做家庭作業,並告訴我們你的嘗試。你的問題的答案非常簡單,你不會通過提交給你的任何進展。 – 2011-04-12 09:27:07