本周学习内容(~2019.2.23)

1  复习了之前学过的 指针 结构体 共用体

2  额外学习了 C++中的用sort对结构数组进行排序

例如对姓名 从小到大排序

#include <stdio.h>
#include <algorithm>  //要用算法头文件
#include <string.h>
using namespace std;

struct student{
    char name[20];
    int id;
} ;

student students[]={"mary",110,"alen",112,"jake",9,"alenx",9};


struct rule1{  //按姓名的大小排序
    bool operator() (const student & s1,const student & s2 )
    {
        if( strcmp(s1.name,s2.name)<0)
            return true;
        return false;


    }


};


int main()
{
    int n=sizeof(students)/sizeof(student);
    sort(students,students+n,rule1());
    for(int i=0;i<4;i++)
    {
        printf("%s\n",students[i].name);
    }
    return 0;
}

运行结果如下 

alen
alenx
jake
mary

--------------------------------
Process exited after 0.02396 seconds with return value 0
请按任意键继续. . .


 除了比较名字 还可以比较id等等 只要将bool operator()(const  ***   & s1,const ***  & s2   ){}

***为结构体的结构名

发布了55 篇原创文章 · 获赞 9 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_42612338/article/details/87857247
今日推荐