淺析C/C++中sort函數(shù)的用法
sort是STL中提供的算法,頭文件為#include<algorithm>以及using namespace std; 函數(shù)原型如下:
template <class RandomAccessIterator> void sort ( RandomAccessIterator first, RandomAccessIterator last ); template <class RandomAccessIterator, class Compare> void sort ( RandomAccessIterator first, RandomAccessIterator last, Compare comp );
使用第一個版本是對[first,last)進(jìn)行升序排序,默認(rèn)操作符為"<",第二個版本使用comp函數(shù)進(jìn)行排序控制,comp包含兩個在[first,last)中對應(yīng)的值,如果使用"<"則為升序排序,如果使用">"則為降序排序,分別對int、float、char以及結(jié)構(gòu)體排序例子如下:
#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};
//結(jié)構(gòu)比較函數(shù)(按照結(jié)構(gòu)中的浮點(diǎn)數(shù)值進(jìn)行排序)
bool compare_struct_float(const product &a,const product &b){
return a.price<b.price;
}
//結(jié)構(gòu)比較函數(shù)(按照結(jié)構(gòu)中的字符串進(jìn)行排序)
bool compare_struct_str(const product &a,const product &b){
return string(a.name)<string(b.name);
}
//打印函數(shù)
void print_int(const int* a,int length){
printf("升序排序后的int數(shù)組:\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數(shù)組:\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數(shù)組:\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("--");
}
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 }};
//整數(shù)排序
sort(array_int,array_int+5);
print_int(array_int,5);
//字符排序
sort(array_char,array_char+5);
print_char(array_char,5);
//浮點(diǎn)排序
sort(array_double,array_double+5);
print_double(array_double,5);
//結(jié)構(gòu)中浮點(diǎn)排序
int len = sizeof(structs)/sizeof(struct product);
sort(structs,structs+len,compare_struct_float);
printf("按結(jié)構(gòu)中float升序排序后的struct數(shù)組:\n");
print_struct_array(structs, len);
//結(jié)構(gòu)中字符串排序
sort(structs,structs+len,compare_struct_str);
printf("按結(jié)構(gòu)中字符串升序排序后的struct數(shù)組:\n");
print_struct_array(structs, len);
}
sort函數(shù)的用法
做ACM題的時候,排序是一種經(jīng)常要用到的操作。如果每次都自己寫個冒泡之類的O(n^2)排序,不但程序容易超時,而且浪費(fèi)寶貴的比賽時間,還很有可能寫錯。STL里面有個sort函數(shù),可以直接對數(shù)組排序,復(fù)雜度為n*log2(n)。使用這個函數(shù),需要包含頭文件。
這個函數(shù)可以傳兩個參數(shù)或三個參數(shù)。第一個參數(shù)是要排序的區(qū)間首地址,第二個參數(shù)是區(qū)間尾地址的下一地址。也就是說,排序的區(qū)間是[a,b)。簡單來說,有一個數(shù)組int a[100],要對從a[0]到a[99]的元素進(jìn)行排序,只要寫sort(a,a+100)就行了,默認(rèn)的排序方式是升序。
拿我出的“AC的策略”這題來說,需要對數(shù)組t的第0到len-1的元素排序,就寫sort(t,t+len);
對向量v排序也差不多,sort(v.begin(),v.end());
排序的數(shù)據(jù)類型不局限于整數(shù),只要是定義了小于運(yùn)算的類型都可以,比如字符串類string。
如果是沒有定義小于運(yùn)算的數(shù)據(jù)類型,或者想改變排序的順序,就要用到第三參數(shù)——比較函數(shù)。比較函數(shù)是一個自己定義的函數(shù),返回值是bool型,它規(guī)定了什么樣的關(guān)系才是“小于”。想把剛才的整數(shù)數(shù)組按降序排列,可以先定義一個比較函數(shù)cmp
bool cmp(int a,int b)
{
return a>b;
}
排序的時候就寫sort(a,a+100,cmp);
假設(shè)自己定義了一個結(jié)構(gòu)體node
struct node{
int a;
int b;
double c;
}
有一個node類型的數(shù)組node arr[100],想對它進(jìn)行排序:先按a值升序排列,如果a值相同,再按b值降序排列,如果b還相同,就按c降序排列。就可以寫這樣一個比較函數(shù):
以下是代碼片段:
bool cmp(node x,node y)
{
if(x.a!=y.a) return x.a
if(x.b!=y.b) return x.b>y.b;
return return x.c>y.c;
}
排序時寫sort(arr,a+100,cmp);
qsort(s[0],n,sizeof(s[0]),cmp);
int cmp(const void *a,const void *b)
{
return *(int *)a-*(int *)b;
}
一、對int類型數(shù)組排序
int num[100];
Sample:
int cmp ( const void *a , const void *b )
{
return *(int *)a - *(int *)b;
}
qsort(num,100,sizeof(num[0]),cmp);
二、對char類型數(shù)組排序(同int類型)
char word[100];
Sample:
int cmp( const void *a , const void *b )
{
return *(char *)a - *(int *)b;
}
qsort(word,100,sizeof(word[0]),cmp);
三、對double類型數(shù)組排序(特別要注意)
double in[100];
int cmp( const void *a , const void *b )
{
return *(double *)a > *(double *)b ? 1 : -1;
}
qsort(in,100,sizeof(in[0]),cmp);
四、對結(jié)構(gòu)體一級排序
struct In
{
double data;
int other;
}s[100]
//按照data的值從小到大將結(jié)構(gòu)體排序,關(guān)于結(jié)構(gòu)體內(nèi)的排序關(guān)鍵數(shù)據(jù)data的類型可以很多種,參考上面的例子寫
int cmp( const void *a ,const void *b)
{
return ((In *)a)->data - ((In *)b)->data ;
}
qsort(s,100,sizeof(s[0]),cmp);
五、對結(jié)構(gòu)體
struct In
{
int x;
int y;
}s[100];
//按照x從小到大排序,當(dāng)x相等時按照y從大到小排序
int cmp( const void *a , const void *b )
{
struct In *c = (In *)a;
struct In *d = (In *)b;
if(c->x != d->x) return c->x - d->x;
else return d->y - c->y;
}
qsort(s,100,sizeof(s[0]),cmp);
六、對字符串進(jìn)行排序
struct In
{
int data;
char str[100];
}s[100];
//按照結(jié)構(gòu)體中字符串str的字典順序排序
int cmp ( const void *a , const void *b )
{
return strcmp( ((In *)a)->str , ((In *)b)->str );
}
qsort(s,100,sizeof(s[0]),cmp);
七、計算幾何中求凸包的cmp
int cmp(const void *a,const void *b) //重點(diǎn)cmp函數(shù),把除了1點(diǎn)外的所有點(diǎn),旋轉(zhuǎn)角度排序
{
struct point *c=(point *)a;
struct point *d=(point *)b;
if( calc(*c,*d,p[1]) < 0) return 1;
else if( !calc(*c,*d,p[1]) && dis(c->x,c->y,p[1].x,p[1].y) < dis(d->x,d->y,p[1].x,p[1].y)) //如果在一條直線上,則把遠(yuǎn)的放在前面
return 1;
else return -1;
}
相關(guān)文章
C語言實現(xiàn)隨機(jī)讀寫文件的函數(shù)詳解
文件的隨機(jī)讀寫,可以在文件中指定的任意位置讀或者寫。這篇文章主要為大家詳細(xì)介紹了C語言實現(xiàn)隨機(jī)讀寫文件的3個函數(shù),感興趣的可以了解一下2023-03-03
C++?中如何結(jié)束?while?(cin>>str)?的輸入
這篇文章主要介紹了C++?中如何結(jié)束?while?(cin>>str)?的輸入,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07
C++?TCP網(wǎng)絡(luò)編程詳細(xì)講解
TCP/IP是一種面向連接的、可靠的、基于字節(jié)流的傳輸層通信協(xié)議,它會保證數(shù)據(jù)不丟包、不亂序。TCP全名是Transmission?Control?Protocol,它是位于網(wǎng)絡(luò)OSI模型中的第四層2022-09-09
C++實現(xiàn)LeetCode(172.求階乘末尾零的個數(shù))
這篇文章主要介紹了C++實現(xiàn)LeetCode(172.求階乘末尾零的個數(shù)),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08
C語言實現(xiàn)學(xué)生管理系統(tǒng)總結(jié)
這篇文章主要為大家詳細(xì)介紹了C語言實現(xiàn)學(xué)生管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-07-07
C/C++獲取主機(jī)網(wǎng)卡MAC地址的三方法
MAC地址(Media Access Control address),又稱為物理地址或硬件地址,是網(wǎng)絡(luò)適配器(網(wǎng)卡)在制造時被分配的全球唯一的48位地址,通過獲取MAC地址可以判斷當(dāng)前主機(jī)的唯一性可以與IP地址綁定并實現(xiàn)網(wǎng)絡(luò)準(zhǔn)入控制,本文給大家介紹了使用C/C++獲取主機(jī)網(wǎng)卡MAC地址的三方法2023-11-11
如何使用visual studio2019創(chuàng)建簡單的MFC窗口(使用C++)
這篇文章主要介紹了如何使用visual studio2019創(chuàng)建簡單的MFC窗口(使用C++),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03

