很久之前做的题
简单的结构体排序
做题体会:使自己更熟练地运用结构体排序
ps:刚学会写文章时怎么让代码高亮QAQ
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
//创建结构体bang,设置三个数据类型,分别用来存储枪的名字,枪的攻击力,枪的价格
struct bang
{
char name[15];
int power;
int price;
};
bool cmp(bang a, bang b); //声明函数cmp
struct bang biubiubiu[100005]; //声明结构数组biubiubiu
int main(){
int test_num, index;
while(scanf("%d", &test_num) != EOF){
for(index = 0; index < test_num; index++)
//分别输入枪的名字,攻击力,价格
scanf("%s%d%d", biubiubiu[index].name, &biubiubiu[index].power, &biubiubiu[index].price);
sort(biubiubiu, biubiubiu + test_num, cmp); //使用sort函数进行结构体排序
for(index = 0; index < test_num; index++)
printf("%s\n", biubiubiu[index].name);
}
return 0;
}
bool cmp(bang a, bang b) //自定义cmp函数
{
if(a.power == b.power){ //如果攻击力相等,按价格排序
if(a.price == b.price){ //如果 价格相同,按字典序排序
return strcmp(a.name, b.name) < 0;
}
else return a.price < b.price;
}
else return a.power > b.power;
}
写于晚自习 2018.10.11 19时