C/c++ sort用法
答案:3 悬赏:20
解决时间 2021-02-16 20:04
- 提问者网友:世勋超人
- 2021-02-16 05:12
C/c++ sort用法
最佳答案
- 二级知识专家网友:毛毛
- 2021-02-16 06:28
.默认的sort函数是按升序排。对应于1)
sort(a,a+n); //两个参数分别为待排序数组的首地址和尾地址
2.可以自己写一个cmp函数,按特定意图进行排序。对应于2)
例如:
int cmp( const int &a, const int &b ){
if( a > b )
return 1;
else
return 0;
}
sort(a,a+n,cmp);
是对数组a降序排序
又如:
int cmp( const POINT &a, const POINT &b ){
if( a.x < b.x )
return 1;
else
if( a.x == b.x ){
if( a.y < b.y )
return 1;
else
return 0;
}
else
return 0;
}
sort(a,a+n,cmp);
是先按x升序排序,若x值相等则按y升序排
sort(a,a+n); //两个参数分别为待排序数组的首地址和尾地址
2.可以自己写一个cmp函数,按特定意图进行排序。对应于2)
例如:
int cmp( const int &a, const int &b ){
if( a > b )
return 1;
else
return 0;
}
sort(a,a+n,cmp);
是对数组a降序排序
又如:
int cmp( const POINT &a, const POINT &b ){
if( a.x < b.x )
return 1;
else
if( a.x == b.x ){
if( a.y < b.y )
return 1;
else
return 0;
}
else
return 0;
}
sort(a,a+n,cmp);
是先按x升序排序,若x值相等则按y升序排
全部回答
- 1楼网友:洎扰庸人
- 2021-02-16 07:08
引用头文件algorithm,直接传入数组,和排序的区间
- 2楼网友:冷風如刀
- 2021-02-16 06:48
首先调用 algorithm
然后sort(起点,终点,比较准则)
比较准则默认是小于等于号,所以sort的结果是从小到大
比较准则可以自拟,比如大于等于,奇偶性等等。这个准则可以是class可以是function#include <iostream> // std::cout
#include <algorithm> // std::sort
#include <vector> // std::vector
bool myfunction (int i,int j) { return (i<j); }
struct myclass {
bool operator() (int i,int j) { return (i<j);}
} myobject;
int main () {
int myints[] = {32,71,12,45,26,80,53,33};
std::vector<int> myvector (myints, myints+8);
// 32 71 12 45 26 80 53 33
// using default comparison (operator <):
std::sort (myvector.begin(), myvector.begin()+4);
//(12 32 45 71)26 80 53 33
// using function as comp
std::sort (myvector.begin()+4, myvector.end(), myfunction);
// 12 32 45 71(26 33 53 80)
// using object as comp
std::sort (myvector.begin(), myvector.end(), myobject);
//(12 26 32 33 45 53 71 80)
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯