通過c++的sort函數實現成績排序功能
sort函數用于C++中,對給定區(qū)間所有元素進行排序,默認為升序,也可進行降序排序。sort函數進行排序的時間復雜度為n*log2n,比冒泡之類的排序算法效率要高,sort函數包含在頭文件為#include<algorithm>的c++標準庫中。
題目描述:
有N個學生的數據,將學生數據按成績高低排序,如果成績相同則按姓名字符的字母排序,如果姓名的字母序也相同,則按照學生的年齡排序,并輸出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ū)的大小,因而多出一個參數。 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
結果

通過運算符重載來實現
#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;
}
由于已經指明了結構體的小于運算符,計算機便知道了該結構體的定序規(guī)則。 sort函數只利用小于運算符來定序,小者在前。于是,我們在調用sort時便不必特別指明排序規(guī)則(即不使用第三個參數)。
總結
到此這篇關于通過c++的sort函數實現成績排序的文章就介紹到這了,更多相關c++ sort函數內容請搜素腳本之家以前的文章或下面相關文章,希望大家以后多多支持腳本之家!

