结构体+sort

一、结构体定义

1、结构体是一种包含了多个变量和数组的集合,这些变量和数组的类型可以相同,也可以不同。
2、结构体是一种构造数据类型。

二、结构体应用

1、常用形式
s1,s2是student结构体数据类型定义的结构体变量

struct student {
char name [20];
int score ;
int age ;
int id;
}s1 ,s2;

2、结构体赋值小技巧

# include <cstdio >
# include <cstring >
using namespace std;
struct node {
        int x, y; char c [100];
        node & operator = ( const node &b){
                y = b.y, x = b.x;
                strcpy (c,b.c);
                return * this ;
           }
}a;
int main (){
        scanf ("%d%d%s" ,&a.x ,&a.y,a.c);
        node b; b = a;
        printf ("%d %d %s\n",b.x,b.y,b.c);
        return 0;
}

三、sort

1、时间复杂度n*log(n) 对数组进行排序的函数。
      使用时在主函数外加入以下内容

# include <algorithm >
using namespace std;

2、sort的基础用法

sort (a,a+n,cmp );

上面例子表示对数组a的0到n-1个元素排序,cmp为自定义的比较函数,不写默认升序排序。
a的位置代表的是进行排序内容的首地址,n是排序的长度,如果需要从下标1开始,则可写成sort(a+1,a+1+n)。

3、sort比较函数

bool cmp (int a,int b){
return a > b;
}

对于上面的数组a进行排序,加入这个cmp函数,即可对数组a进行降序排序,如果改为小于,则和默认排序一样为升
序排序

四、结构体排序的基本用法

1、使用时在sort函数中使用cmp函数,根据题目要求对内部指定元素排序
2、示例意为对内部x由小到大排序,如果x相等对y由小到大排序,如果y相等那么按照字典序最小对c排序
3、根据题目要求决定结构体内部排序方式

bool cmp ( node a, node b){
    if (a.x == b.x){
        if (a.y == b.y) return strcmp (a.c,b.c) <0;
        else return a.y < b.y;
    } return a.x < b.x;
}
#include <stdio.h>
#include <cstring>
#include <algorithm>
using namespace std;

/*输入五个人的姓名和成绩 成绩由小到大排序 成绩相同按姓名字典序最小排序*/
/*
abcd
czde
aabd

aabd
abcd
czde  按字典序最小排序 
*/
struct node{
	char name[20];
	int score;
}stu[100];

bool cmp(node a,node b){
	if (a.score == b.score) return strcmp(a.name,b.name)<0;
	return a.score < b.score;
}

int main(){
	int n = 5;
	for (int i = 0;i <n ; ++i) scanf("%s%d",stu[i].name,&stu[i].score);
	
	sort(stu,stu+n,cmp);
	
	for (int i = 0;i < n; ++i) printf("%s %d\n",stu[i].name,stu[i].score);
	return 0;
}
/*
input
aa 100
cc 89
dd 98
bb 73
ee 100

output
bb 73
cc 89
dd 98 
aa 100
ee 100

*/

五、练习题

https://vjudge.net/contest/239558

密码:hpuacm

猜你喜欢

转载自blog.csdn.net/WWJ970529/article/details/81226356