溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

通過c++的sort函數(shù)實現(xiàn)成績排序功能

發(fā)布時間:2020-09-07 19:00:04 來源:腳本之家 閱讀:220 作者:fourpoint 欄目:編程語言

sort函數(shù)用于C++中,對給定區(qū)間所有元素進行排序,默認為升序,也可進行降序排序。sort函數(shù)進行排序的時間復雜度為n*log2n,比冒泡之類的排序算法效率要高,sort函數(shù)包含在頭文件為#include<algorithm>的c++標準庫中。

題目描述:

有N個學生的數(shù)據(jù),將學生數(shù)據(jù)按成績高低排序,如果成績相同則按姓名字符的字母排序,如果姓名的字母序也相同,則按照學生的年齡排序,并輸出N個學生排序后的信息。

#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
struct E {
 char name[101];
 int age;
 int score;
}buf[1000];

bool cmp(E a, E b) {
 if (a.score != b.score) return a.score < b.score;
 int tmp = strcmp(a.name, b.name);
 if (tmp != 0) return tmp < 0;
 else return a.age < b.age;
}
int main() {
 int n;
 while (scanf_s("%d", &n) != EOF) {
 for (int i = 0; i < n; i++) {
 scanf_s("%s%d%d", buf[i].name,sizeof(buf[i].name), &buf[i].age, &buf[i].score);
 }
 sort(buf, buf + n, cmp);
 printf("\n");
 for (int i = 0; i < n; i++) {
 printf("%s %d %d\n", buf[i].name, buf[i].age, buf[i].score);
 } 
 }
 return 0;
}

注意事項

scanf和scanf_s區(qū)別使用,scanf_s需要標明緩沖區(qū)的大小,因而多出一個參數(shù)。 Unlike scanf and wscanf, scanf_s and wscanf_s require you to specify buffer sizes for some parameters. Specify the sizes for all c, C, s, S, or string control set [] parameters. The buffer size in characters is passed as an additional parameter. It immediately follows the pointer to the buffer or variable. For example, if you're reading a string, the buffer size for that string is passed as follows:

char s[10];
scanf_s("%9s", s, (unsigned)_countof(s)); // buffer size is 10, width specification is 9

微軟參考文檔

結果

通過c++的sort函數(shù)實現(xiàn)成績排序功能

通過運算符重載來實現(xiàn)

#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
struct E {
 char name[101];
 int age;
 int score;
 bool operator <(const E &b) const {
 if (score != b.score) return score < b.score;
 int tmp = strcmp(name, b.name);
 if (tmp != 0) return tmp < 0;
 else return age < b.age;
 }
}buf[1000];

int main() {
 int n;
 while (scanf_s("%d", &n) != EOF) {
 for (int i = 0; i < n; i++) {
 scanf_s("%s%d%d", buf[i].name,sizeof(buf[i].name), &buf[i].age, &buf[i].score);
 }
 sort(buf, buf + n);
 printf("\n");
 for (int i = 0; i < n; i++) {
 printf("%s %d %d\n", buf[i].name, buf[i].age, buf[i].score);
 } 
 }
 return 0;
}

由于已經(jīng)指明了結構體的小于運算符,計算機便知道了該結構體的定序規(guī)則。 sort函數(shù)只利用小于運算符來定序,小者在前。于是,我們在調(diào)用sort時便不必特別指明排序規(guī)則(即不使用第三個參數(shù))。

總結

到此這篇關于通過c++的sort函數(shù)實現(xiàn)成績排序的文章就介紹到這了,更多相關c++ sort函數(shù)內(nèi)容請搜素億速云以前的文章或下面相關文章,希望大家以后多多支持億速云!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI