通過c++的sort函數(shù)實現(xiàn)成績排序功能
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
結(jié)果
通過運算符重載來實現(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)指明了結(jié)構(gòu)體的小于運算符,計算機便知道了該結(jié)構(gòu)體的定序規(guī)則。 sort函數(shù)只利用小于運算符來定序,小者在前。于是,我們在調(diào)用sort時便不必特別指明排序規(guī)則(即不使用第三個參數(shù))。
總結(jié)
到此這篇關于通過c++的sort函數(shù)實現(xiàn)成績排序的文章就介紹到這了,更多相關c++ sort函數(shù)內(nèi)容請搜素腳本之家以前的文章或下面相關文章,希望大家以后多多支持腳本之家!
相關文章
Vs2019+Qt+Opencv環(huán)境配置心得(圖文)
這篇文章主要介紹了Vs2019+Qt+Opencv環(huán)境配置心得(圖文),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-08-08C語言全面細致講解單雙精度float與double的使用方法
C語言中小數(shù)的數(shù)據(jù)類型為 float 或 double:float 稱為單精度浮點數(shù),double 稱為雙精度浮點數(shù)。不像整數(shù),小數(shù)的長度始終是固定的,float 占用4個字節(jié),double 占用8個字節(jié)2022-05-05