C语言sortabc函数 c语言 sort函数

sort函数在C语言中的作用是啥?1、sort()函数描述:对给定区间所有元素进行排序 。
sort()函数语法:sort(begin,end),表示一个范围 。
2、sort()函数举例:
#include algorithm
#include iostream
using namespace std;
main()
{
int a[11]={2,4,8,5,7,1,10,6,9,3};//a的长度=待排数据个数+1
sort(a,a+10);//对[a,a+10)排序
for(int i=0;i10;++i) couta[i]endl;
}
c语言中sort的用法详解c语言C语言sortabc函数的学习很多是比较复杂的 , 那么c语言中sort的用法的用法你知道吗C语言sortabc函数?下面C语言sortabc函数我就跟你们详细介绍下c语言中sort的用法的用法 , 希望对你们有用 。
c语言中sort的用法的用法
sort是STL中提供的算法,头文件为#includealgorithm以及using namespace std; 函数原型如下C语言sortabc函数:
?
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;
}
//结构比较函数(按照结构中的字符串进行排序)
bool compare_struct_str(const product a,const product b){
return string(a.name)string(b.name);
}
//打印函数
void print_int(const int* a,int length){
printf("升序排序后的int数组:\n");
for(int i=0; ilength-1; i++)
printf("%d ",a[i]);
printf("%d\n",a[length-1]);
}
void print_char(const char* a,int length){
printf("升序排序后的char数组:\n");
for(int i=0; ilength-1; i++)
printf("%c ",a[i]);
printf("%c\n",a[length-1]);
}
void print_double(const double* a,int length){
printf("升序排序后的dobule数组:\n");
for(int i=0; ilength-1; i++)
printf("%.2f ",a[i]);
printf("%.2f\n",a[length-1]);
}
void print_struct_array(struct product *array, int length)
{
for(int i=0; ilength; i++)
printf("[ name: %s \t price: $%.2f ]\n", array[i].name, array[i].price);
puts("--");
}
void main()
{
struct product structs[] = {{"mp3 player", 299.0f}, {"plasma tv", 2200.0f},
{"notebook", 1300.0f}, {"smartphone", 499.99f},
{"dvd player", 150.0f}, {"matches", 0.2f }};

推荐阅读