sort函数c语言结构体 sort语句c语言

关于结构体排序和sort函数#include iostream
#include cstring
using namespace std;
struct people{
int year;
int month;
int day;
char name[50];
};
bool smaller(people a,people b) {
if(a.yearb.year) return true;
if(a.year == b.yeara.monthb.month) return true;
if(a.year == b.yeara.month == b.montha.dayb.day) return true;
return false;
}
void resolve(char s[], int *year, int *month, int *day) {
int i = 0;
*year = *month = *day = 0;
while(s[i] != '/') *month = 10 * (*month) + s[i++] - '0';
++i;
while(s[i] != '/') *day = 10 * (*day) + s[i++] - '0';
++i;
while(s[i] != '\0') *year = 10 * (*year) + s[i++] - '0';
}
void sort_name(people a[], int n) {
int i,j,k;
people t;
for(i = 0; in - 1; ++i) {
k = i;
for(j = i + 1; jn; ++j) {
if(strcmp(a[j].name,a[k].name)0)
k = j;
}
if(k != i) {
t = a[k];
a[k] = a[i];
a[i] = t;
}
}
}
void sort_birthday(people a[], int n) {
int i,j,k;
people t;
for(i = 0; in - 1; ++i) {
k = i;
for(j = i + 1; jn; ++j) {
if(smaller(a[k],a[j]))
k = j;
}
if(k != i) {
t = a[k];
a[k] = a[i];
a[i] = t;
}
}
}
int main() {
people p[1001];
int i,n;
char birthday[12];
cinn;
for(i = 0;in;i++) {
cinp[i].namebirthday;
resolve(birthday,p[i].year,p[i].month,p[i].day);
}
sort_name(p,n); // 先按姓名排序
sort_birthday(p,n); // 再按年龄排序
for(i = 0; in; i++)
printf("%s\n",p[i].name);
return 0;
}
c语言中sort的用法详解c语言的学习很多是比较复杂的 , 那么c语言中sort的用法的用法你知道吗?下面我就跟你们详细介绍下c语言中sort的用法的用法,希望对你们有用 。
c语言中sort的用法的用法
sort是STL中提供的算法,头文件为#includealgorithm以及using namespace std; 函数原型如下:
?
1
2
3
4
5
template class RandomAccessIterator
void sort ( RandomAccessIterator first, RandomAccessIterator last );
template class RandomAccessIterator, class Compare
void sort ( RandomAccessIterator first, RandomAccessIterator last, Compare comp );
使用第一个版本是对[first,last)进行升序排序,默认操作符为"" , 第二个版本使用comp函数进行排序控制,comp包含两个在[first,last)中对应的值,如果使用""则为升序排序,如果使用""则为降序排序 , 分别对int、float、char以及结构体排序例子如下:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#includestdio.h
#includealgorithm
#includestring
using namespace std;
struct product{
char name[16];
float price;
};
int array_int[5]={4,1,2,5,3};
char array_char[5]={'a','c','b','e','d'};
double array_double[5]={1.2,2.3,5.2,4.6,3.5};
//结构比较函数(按照结构中的浮点数值进行排序)
bool compare_struct_float(const product a,const product b){
return a.priceb.price;

推荐阅读