首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

怎么对自己定义的结构类型的容器按照某项进行排序

2013-03-17 
如何对自己定义的结构类型的容器按照某项进行排序void main(){struct costindex{int indexfloat value}

如何对自己定义的结构类型的容器按照某项进行排序


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();
}

热点排行