很久之前做的題
簡單的結構體排序
做題體會:使自己更熟練地運用結構體排序
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時