sort如何排序自定义数据类型
问:使用stl中的sort函数如何排序自定义数据类型,按其中的一个量为序,我的代码如下,可是有错误,好像是排序的过程中要insert,出错了。。。
#include <iostream>#include <vector>#include <algorithm>using namespace std;struct costnode{ int fromVillage; int endVillage; int cost;};costnode cost[101];bool cmp(int x,int y){ return cost[x].cost>cost[y].cost;}int main(){ int N,M; while (cin>>N>>M&&N!=0) { int i = 0 , j = 0 , fromVillage = 0 , endVillage = 0 , icost = 0; for (i=0;i<N;i++) { cin>>fromVillage>>endVillage>>icost; cost[i].fromVillage = fromVillage; cost[i].endVillage = endVillage; cost[i].cost = icost; } sort(cost+1,cost+M,cmp); } return 0;}bool cmp(costnode x,costnode y){ return x.cost>y.cost;}
[解决办法]