建立了一个结构体,然后用容器进行存放,想对其进行排序。vector支持sort函数,但是需要自己指定排序函数。
方法如下:
1.需要包含头文件
#include <algorithm>
#include <vector>
using namespace std;
2.声明结构体
typedef struct mydata
{
int index;
float data;
}mydata;
3.定义比较函数
bool SortByIndex(const mydata &d1,const mydata &d2)//容器的比较函数
{
return (d1.index> d2.index);//降序排列
}
4.调用 v_data为需要进行排序的vector变量
std::sort(v_data.begin(),v_data.end(),SortByIndex);
运行即可。