【发布时间】:2011-02-24 03:52:00
【问题描述】:
我正在尝试使用 STL 中的qsort 对边缘数组进行排序:
struct edge
{
int w,v,weight;
};
按重量计算。我正在尝试的是:
int compare_e(const void *a, const void *b)
{
return ( *(edge *)a->weight - *(edge *)b->weight );
};
但我明白了:
`const void*' 不是 指向对象类型
编辑: 好的 thx,现在我的代码已编译,但排序似乎不能 100% 工作......
#include <cstdlib>
#include <iostream>
struct edge
{
int w,v,weight;
};
struct edge_ID:edge
{
int id;
};
int compare_e(const void *a, const void *b)
{
return ( ((edge *)a)->weight > ((edge *)b)->weight );
};
int main()
{
using namespace std;
edge *tab = new edge[100];
for(int i = 0; i < 100; i++)
{
tab[i].weight = rand() % 100;
cout << i << " => " << tab[i].weight << endl;
}
qsort(tab, 100, sizeof(edge), compare_e);
cout << "AFTER:" << endl;
for(int i = 0; i < 100; i++)
{
cout << i << " => " << tab[i].weight << endl;
}
system("PAUSE");
return EXIT_SUCCESS;
}
我的号码放错地方了……
【问题讨论】:
-
为什么不试试 std::sort 更容易
-
排序是否只适用于迭代器?
-
对于数组指针是迭代器
-
比较函数还不正确。返回负数表示较小,0 表示相等,正数表示较大。