栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

通过c++的sort函数实现成绩排序功能

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

通过c++的sort函数实现成绩排序功能

sort函数用于C++中,对给定区间所有元素进行排序,默认为升序,也可进行降序排序。sort函数进行排序的时间复杂度为n*log2n,比冒泡之类的排序算法效率要高,sort函数包含在头文件为#include的c++标准库中。

题目描述:

有N个学生的数据,将学生数据按成绩高低排序,如果成绩相同则按姓名字符的字母排序,如果姓名的字母序也相同,则按照学生的年龄排序,并输出N个学生排序后的信息。

#include
#include
#include
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 %dn", buf[i].name, buf[i].age, buf[i].score);
 } 
 }
 return 0;
}

注意事项

scanf和scanf_s区别使用,scanf_s需要标明缓冲区的大小,因而多出一个参数。 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
#include
#include
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 %dn", buf[i].name, buf[i].age, buf[i].score);
 } 
 }
 return 0;
}

由于已经指明了结构体的小于运算符,计算机便知道了该结构体的定序规则。 sort函数只利用小于运算符来定序,小者在前。于是,我们在调用sort时便不必特别指明排序规则(即不使用第三个参数)。

总结

到此这篇关于通过c++的sort函数实现成绩排序的文章就介绍到这了,更多相关c++ sort函数内容请搜素考高分网以前的文章或下面相关文章,希望大家以后多多支持考高分网!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/62015.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号