C++ sort函数的用法
C++ sort函數的用法
?
STL有個排序函數sort,可以直接對數組和向量排序。
一、功能:給定區間所有元素進行排序
二、頭文件: #include <algorithm>
三、sort函數的參數:可以傳兩個參數或三個參數。
第一個參數:要排序的區間首地址,
第二個參數:區間尾地址的下一地址。也就是說,排序的區間是[a,b)。
例如:數組int a[100],sort(a,a+100)是對從a[0]到a[99]的元素進行排序,默認的排序方式是升序。 對向量v排序:sort(v.begin(),v.end());
排序的數據類型不局限于整數,只要是定義了小于運算的類型都可以,比如字符串類string。
第三參數:比較函數。如果是沒有定義小于運算的數據類型,或者想改變排序的順序,就要用到第三參數的比較函數。比較函數是一個自己定義的函數,返回值是bool型,它規定了什么樣的關系才是“小于”。
四、排序方法:
1、整數數組降序排序
定義一個比較函數: bool cmp(int a, int b) { return a>b; }
排序: sort(a,a+100,cmp);
2、結構體數組排序
例如: 如下結構體node數組
struct node{ int a; int b; double c;}
node arr[100],
要求對數組arr進行排序:先按a值升序排列,如果a值相同,再按b值降序排列,如果b還相同,就按c降序排列。定義如下一個比較函數:
bool cmp(node x,node y)
{ if (x.a!=y.a) return x.a>y.a;
If (x.b!=y.b) return x.b>y.b;
return return x.c>y.c; }
sort(arr,a+100,cmp);
?
五、程序示例:
#include<stdio.h>
#include<algorithm>
#include<string>
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.price<b.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; i<length-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; i<length-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; i<length-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; i<length; i++)
printf("[ name: %s \t price: $%.2f ]\n", array[i].name, array[i].price);
puts("--");
}
int 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 } };
//整數排序
sort(array_int,array_int+5);
print_int(array_int,5);
//字符排序
sort(array_char,array_char+5);
print_char(array_char,5);
//浮點排序
sort(array_double,array_double+5);
print_double(array_double,5);
//結構中浮點排序
int len = sizeof(structs)/sizeof(struct product);
sort(structs,structs+len,compare_struct_float);
printf("按結構中float升序排序后的struct數組:\n");
print_struct_array(structs, len);
//結構中字符串排序
sort(structs,structs+len,compare_struct_str);
printf("按結構中字符串升序排序后的struct數組:\n");
print_struct_array(structs, len);
}
轉載于:https://www.cnblogs.com/2014acm/p/3884735.html
總結
以上是生活随笔為你收集整理的C++ sort函数的用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: win10怎么强制清除数据库 Win10
- 下一篇: bios 无法进入u盘启动不了怎么办 如