C sort函式用法

2021-10-02 16:36:21 字數 1476 閱讀 3766

c++ sort函式用法sort函式有三個引數:sort(a,a+2,cmp)

(1)第乙個是要排序的陣列的起始位址。

(2)第二個是結束的位址。

(3)第三個引數是排序的方法,預設為公升序排列,如需要降序排列,則需要提供bool cmp()比較函式。

注意:在c++中,使用sort函式需要 #include < algorithm >標頭檔案

另外,sort的前兩個引數不是陣列下標,是迭代器。sort(a,a+2)就是將第

一、二個元素進行排序,sort(a+2,a+4)就是將第

三、四個元素進行排序,包括後邊的數,但不包括前邊的。 如:(a,a+2] (a+2,a+4]。

接下來會展示三種情況下cmp函式的用法:

1、整型資料和實型資料比較

int型資料

bool

cmp(

int a,

int b)

int a[10]

;sort

(a,a+

10,cmp)

;

float型資料

bool

cmp(

float a,

float b)

int a[10]

;sort

(a,a+

10,cmp)

;

cmp函式有如下的寫法:

bool

cmp(

const

int&a,

const

int&b)

int a[10]

;sort

(a,a+

10,cmp)

;

其中,int這種寫法是值傳遞,const int&則是引用傳遞。

「值傳遞」——函式將自動產生臨時變數用於複製該引數,效率較低。

「引用傳遞」——借用一下引數的別名,不需要產生臨時物件,效率較高。

2、char型和string型資料比較

char型資料比較

bool

cmp(

char a,

char b)

string型資料比較

bool

cmp(string a,string b)

另外要注意的是,char型字串不能用大於小於號來排順序,要用strcmp函式。

strcmp函式標頭檔案為#include

3、結構體型別比較

struct student

stu[

100]

;bool

cmp(student a,student b)

//從小到大排序

sort

(stu,stu+

100,cmp)

;

C sort 函式用法

msdn中的定義 template voidsort ranit first,ranit last 1 template voidsort ranit first,ranit last,pred pr 2 標頭檔案 include using namespace std 1.預設的sort函式是按公...

C sort 函式用法

msdn中的定義 template voidsort ranit first,ranit last 1 template voidsort ranit first,ranit last,pred pr 2 標頭檔案 include using namespace std 1.預設的sort函式是按公...

C sort函式用法

from 最近演算法作業經常需要排序。偶是乙個很懶的人,於是一直用c 的sort進行排序 不少同志對此心存疑慮,所以今天就寫一寫sort的用法。宣告 此用法是從某大牛的程式中看到的,其實偶只是拿來用,不知所以然,飄走 msdn中的定義 template voidsort ranit first,ra...