这个代码在这里显示了这样做的方法有两种:
的第一种方法确实使用的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