Structure sorting sdnuoj1028. Contact

The function strcmp()
is only used for string comparison. In essence, it compares asc codes
. The return value is only positive and negative numbers and 0; the
returned positive and negative numbers are random;
if the return value is less than 0, it means str1 is less than str2.
If the return value is greater than 0, it means that str1 is greater than str2.
If the return value is equal to 0, it means that str1 is equal to str2.

int strcmp(const char *str1, const char *str2)/函数的声明与使用
#include <stdio.h>
#include <string.h>
 
int main ()
{
    
    
   char str1[15];
   char str2[15];
   int ret;
 
 
   strcpy(str1, "abcdef");//也可以通过cin输入字符串,cin>>str1>>str2;
   strcpy(str2, "ABCDEF");
 
   ret = strcmp(str1, str2);
 
   if(ret < 0)
   {
    
    
      printf("str1 小于 str2");//一般都用的这个,因为都是判断谁的首字母在前面之类的
   }
   else if(ret > 0) 
   {
    
    
      printf("str1 大于 str2");
   }
   else 
   {
    
    
      printf("str1 等于 str2");
   }
   
   return(0);
}

int strcmp(const char *str1, const char *str2)

Structure (struct) is a data collection composed of a series of data of the same type or different types, also called structure.
Structure declaration

struct person
{
    
    
    int a;//定义一个整形变量a
    int ar[20];//定义一个整形数组
    char b;//定义一个字符变量b;
    float c;//定义一个浮点数变量c;
};

AC code offer

#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <stdlib.h>
#include <sstream>
#include <map>
#include <set>
typedef long long ll;
using namespace std;
int ar[100005];
int sum[100005];
struct person//定义一个结构体person
{
    
    
    char name[55];
    int year;
    int month;
    int day;
};
bool cmp(person a, person b)//定义一个bool型的函数cmp。来对数据进行排序
{
    
    
    if(a.year > b.year) return 0;//bool是一个只返回真或假的函数,0为假,交换,1为真,交换
    else if(a.year < b.year) return 1;
    else{
    
    
        if(a.month > b.month) return 0;
        else if(a.month <b.month) return 1;
        else {
    
    
            if(a.day > b.day) return 0;
            else if(a.day > b.day) return 1;
            else {
    
    strcmp(a.name, b.name)<0;}//将姓名的首字母按降序排列
        }
    }
}
int  main()
{
    
    
    int n;
    cin>>n;
    person kk[10005];
    bool cmp(person a, person b);//一定要写这个bool 
    for(int i = 0; i < n; i++)
    {
    
    
        scanf("%s %d/%d/%d",&kk[i].name, &kk[i].month, &kk[i].day, &kk[i].year);//注意注意注意 用scanf一定要用&,不然会没有输出的!!!!!!!一定要注意,我已经跌好几次了,所以改用了cin
    }
    sort(kk, kk+n, cmp);//sort排序
    for(int i = 0; i < n; i++)
    {
    
    
        cout<<kk[i].name<<'\n';//记得换行!
    }

    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_51216553/article/details/109536642