博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++ sort()函数和C qsort()函数用法总结
阅读量:7112 次
发布时间:2019-06-28

本文共 2154 字,大约阅读时间需要 7 分钟。

C++sort函数

头文件:

#include 

用法:

sort(begin,end,method);//如果method缺省,则默认从小到大排序

用法示例:

1.缺省用法:从小到大排序

int a[]={
2,3,10,7,8,1,0,12};//数组 sort(a,a+8); for(int i=0;i!=8;++i) cout<
<<" ";
vector
v;//vector容器 v.push_back(2); v.push_back(3); v.push_back(10); v.push_back(7); sort(v.begin(),v.end()); for(auto it=v.begin();it!=v.end();++it) cout<<*it<<" ";

2.写入比较方法用法

bool comp(const int &a,const int &b){    return a>b;//comp函数实现从大到小排序;如果想升序,可写为a
()int main(){ int a[]={
2,3,10,7,8,1,0,12}; sort(a,a+8,comp);//写入Compare Method for(int i=0;i!=8;++i) cout<
<<" ";}
//对结构体进行排序//排序方法:先按first_x进行升序,如果first_x相同,则按second_y降序struct TestCase{    int first_x;    int second_y;}s[10];bool comp(const TestCase &a,const TestCase &b){    if(a.first_x!=b.first_x)        return a.first_x
b.second_y;}//注:也可进行操作符重载,然后按默认(缺省)或者写入greater进行升序(降序)排列,此处不再详述

C qsort函数

头文件:

#include 

用法:

void qsort(void *base,int nelem,int width,int (*fcmp)(const void *,const void *));//其中base是排序的一个集合数组,num是这个数组元素的个数,width是一个元素的大小,comp是一个比较函数。qsort(begin,lenth,width,comp);//comp函数格式为:int comp(const void*a,const void*b)//注:comp传入的指针为无类型指针,需要进行类型转换

用法示例:

//一个C语言实例对数组a[]实现升序排列int comp(const void *a,const void *b){    return (*(int*)a)-(*(int*)b);//将void*转换为int*}int main(){     int a[]={
2,3,10,7,8,1,0,12}; qsort(a,8,sizeof(int),comp); for(int i=0;i<8;++i) printf("%d ",a[i]); return 0;}
//对结构体关键字进行的排序//排序方法:同前#include 
#include
struct TestCase{ int first_x; int second_y;}s[10];int comp(const void *a,const void *b){ struct TestCase *p=(struct TestCase*)a; struct TestCase *q=(struct TestCase*)b; if(p->first_x!=q->first_x) return p->first_x-q->first_x; else return q->second_y-p->second_y;}int main(){ s[0].first_x=1; s[0].second_y=1; s[1].first_x=2; s[1].second_y=2; s[2].first_x=2; s[2].second_y=3; qsort(s,3,sizeof(struct TestCase),comp); for(int i=0;i<3;++i) printf("%d %d\n",s[i].first_x,s[i].second_y); return 0;}

转载于:https://www.cnblogs.com/xLester/p/7570367.html

你可能感兴趣的文章
手动修改IP和MAC地址
查看>>
(20)Powershell中的特殊运算符
查看>>
IIS 7.0 六大新特性
查看>>
32. mac上传下载文件到远程服务器scp
查看>>
阿里云数据库2-3月刊:阿里云峰会云数据库四大发布
查看>>
像Google一样构建机器学习系统 - 利用MPIJob运行ResNet101
查看>>
Django book 笔记---Form表单
查看>>
为什么我不同意建房子
查看>>
使用webpack实现jquery按需加载
查看>>
phalcon queueing使用心得
查看>>
The difference between hard and soft links
查看>>
Python学习日记---字符串
查看>>
脚本入门之算术运算
查看>>
授之以渔-运维平台Saltstack Web 管理一(Returnner篇)
查看>>
PHP操作XML(二)——单词翻译功能
查看>>
Android系统的智能指针(轻量级指针、强指针和弱指针)的实现原理分析(5)...
查看>>
Struts2、Spring和Hibernate应用实例
查看>>
计算webView的高度
查看>>
把常见的编码类型文件(ASCI、Unicode、utf-8)读出到std::string中
查看>>
linux下tomcat服务的相关命令
查看>>