怎么对自己定义的结构类型的容器按照某项进行排序
如何对自己定义的结构类型的容器按照某项进行排序
我怎么可以按照value值的由大到小的顺序排序;
比如上述cost中排序后
for(int i=0;i<3;i++)
{
cout<<cost[i].value<<" "<<cost[i].index<<endl;
}
的输出为40,2
20,1
0,0
}
------解决方案--------------------
void main()
{
struct costindex
{
int index;
float value;
};
vector<costindex> cost;
for(int i=0;i<3;i++)
{
cost[i].value=20*i;
cost[i].index=i;
}
}
我怎么可以按照value值的由大到小的顺序排序;
比如上述cost中排序后
for(int i=0;i<3;i++)
{
cout<<cost[i].value<<" "<<cost[i].index<<endl;
}
的输出为40,2
20,1
0,0
}
------解决方案--------------------
// consoleTest.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
typedef struct COSTINDEX
{
int index;
int value;
}CostIndex;
bool cmpCostIndex(CostIndex& a, CostIndex& b)
{
return a.value > b.value;
}
void main()
{
vector<CostIndex> cost(3);
for(int i=0;i<3;i++)
{
cost[i].value=20*i;
cost[i].index=i;
}
sort(cost.begin(), cost.end(), cmpCostIndex);
vector<CostIndex>::const_iterator iter = cost.begin();
for (; iter != cost.end(); ++iter)
{
cout<< iter->value << " " << iter->index <<endl;
}
getchar();
}