帶你了解C++中的sort函數(shù)
sort( )
使用方法:
sort(首元素地址(必填),尾元素地址的下一個(gè)地址(必填),比較函數(shù)(非必填))
必須加上頭文件:#include< algorithm >和using namespace std;
舉個(gè)栗子:
#include<stdio.h>
#include<algorithm>
using namespace std;
int main()
{
int book[5]={5, 4, 2, 8, 7};
sort(book,book+5);
int i;
for(i=0;i<5;i++)
{
printf("%d ",book[i]);
}
return 0;
}
char型數(shù)組
#include<stdio.h>
#include<algorithm>
using namespace std;
int main()
{
char book[]={'A','L','B','Q'};
sort(book,book+4);
int i;
for(i=0;i<4;i++)
{
printf("%c ",book[i]);
}
return 0;
}
我們上面的排序都是由小到大排序,然后我們可以使用cmp來自定義排序方式。
#include<stdio.h>
#include<algorithm>
using namespace std;
bool cmp(int a,int b)
{
return a>b;//a大于b時(shí),把a(bǔ)放在前面
}
int main()
{
int book[ ]={5,2,0,1,3,1,4};
sort(book,book+7,cmp);
int i;
for(i=0;i<7;i++)
{
printf("%d ",book[i]);
}
return 0;
}
char型數(shù)組
#include<stdio.h>
#include<algorithm>
using namespace std;
bool cmp(char a,char b)
{
return a>b;
}
int main()
{
char book[]={'Q','S','A','Z','L'};
sort(book,book+5,cmp);
int i;
for(i=0;i<5;i++)
{
printf("%c ",book[i]);
}
return 0;
}
結(jié)構(gòu)體數(shù)組排序
#include<stdio.h>
#include<algorithm>
using namespace std;
struct node
{
int x,y;
}book[10];
bool cmp(node a,node b)
{
return a.x>b.x;//按x由大到小排序
}
int main()
{
book[0].x=5;
book[0].y=2;
book[1].x=0;
book[1].y=5;
book[2].x=2;
book[2].y=1;
sort (book,book+3,cmp);
int i;
for(i=0;i<3;i++)
{
printf("%d %d \n",book[i].x,book[i].y);
}
return 0;
}
#include<stdio.h>
#include<algorithm>
using namespace std;
struct node
{
int x,y;
}book[10];
bool cmp(node a,node b)
{
if(a.x!=b.x)
return a.x>b.x;//x不等時(shí)按x排序
else return a.y<b.y;//x相等時(shí)按y排序
}
int main()
{
book[0].x=5;
book[0].y=2;
book[1].x=0;
book[1].y=5;
book[2].x=2;
book[2].y=1;
sort (book,book+3,cmp);
int i;
for(i=0;i<3;i++)
{
printf("%d %d \n",book[i].x,book[i].y);
}
return 0;
}
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
C++實(shí)現(xiàn)字符串類型相互轉(zhuǎn)換的代碼示例
在C/C++編程中,字符串是非?;A(chǔ)且常用的數(shù)據(jù)類型,但是由于不同的編程語言或標(biāo)準(zhǔn)庫可能采用不同的字符串類型,因此在不同的應(yīng)用場景下可能需要進(jìn)行字符串類型的相互轉(zhuǎn)換,本文將介紹如何在C/C++中將char*,std::string,QString,CString/MFC?String相互轉(zhuǎn)換2023-06-06
Visual Studio Code (vscode) 配置 C / C++ 環(huán)境的流程
這篇文章主要介紹了Visual Studio Code (vscode) 配置 C / C++ 環(huán)境的流程,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-09-09
C++中隱式類型轉(zhuǎn)換學(xué)習(xí)筆記
在本篇文章里小編給大家整理的是一篇關(guān)于C++中隱式類型轉(zhuǎn)換學(xué)習(xí)筆記內(nèi)容,有興趣的跟著小編來學(xué)習(xí)下吧。2020-02-02
C++基于Directx MMX實(shí)現(xiàn)的圖像灰度轉(zhuǎn)換代碼
這篇文章主要介紹了C++基于Directx MMX實(shí)現(xiàn)的圖像灰度轉(zhuǎn)換代碼,需要的朋友可以參考下2014-08-08
Visual Studio Code運(yùn)行C++代碼時(shí)顯示CLOCKS_PER_SEC未定義的問題及解決方法
這篇文章主要介紹了解決Visual Studio Code運(yùn)行C++代碼時(shí)顯示CLOCKS_PER_SEC未定義的問題,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-04-04

