您的位置:首页 > 其它

简单的结构体排序

2017-02-11 22:04 113 查看
//在网上搜索结构体排序很多都是使用冒泡排序来进行

//学习了lambda表达式后,产生用这个来作为谓词对结构体进行排序

//很简单的结构体排序,结构体只是很简单的string类型+int类型

#include<string>

#include<iostream>

#include<algorithm>

#include<vector>

#include<functional>

#include<numeric>

using namespace std;

//定义结构体

struct test

{

public:

string name;

int score;

test () =default;

};

int main()

{

vector<test> aaa;

test tem;

int n;

//只举了3个例子;

for(n=1;n<=3;++n)

{

cin>>tem.name>>tem.score;

aaa.push_back(tem);

}

//排序部分使用了<algorithm>库的sort函数,使用一个lambda表达式来作为谓词

//如果用函数的话直接写上函数的名字

sort(aaa.begin(),aaa.end(),[=](test a,test b){return a.score<b.score;});

for(auto c:aaa)

cout<<c.name<<":"<<c.score<<endl;

system("pause");

return EXIT_SUCCESS;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: