Vector的自动排序Sort

来源:互联网 发布:pe工具箱 知乎 编辑:程序博客网 时间:2024/05/16 17:26

建立了一个结构体,然后用容器进行存放,想对其进行排序。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); 


运行即可。

0 0
原创粉丝点击