C++sort函数关于数组、容器vector、字符串类string排序

一、作用:

C++中自带的排序方法,需要提供序列的头、尾地址,和排序方式(降序或升序)。其中时间复杂度为n*log2(n),效率较高!

sort函数就好比一条糅乱的绳子,只有抓住头和尾,甩动起来就可以让绳子拉直,有序,再就是需要考虑一下是从头开始甩呢?还是从尾开始甩就可以了。

二、用法:

(1)头函数:#include <algorithm>   

  std::sort

(2)参数:sort(start,end,ways)

start:序列头地址

end:序列尾地址

ways:排序方式,升序或降序,默认排序为升序。可自定义,也可以使用内置排序方法:less<数据类型>(),greater<数据类型>()   包含在std::less    std::greater中

三、例子:

扫描二维码关注公众号,回复: 3023415 查看本文章

(1)数组

#include<iostream>

#include<algorithm>

using namespace std;

int main()

{

 int a[10]={9,6,3,8,5,2,7,4,1,0};

 for(int i=0;i<10;i++)

 cout<<a[i]<<endl;

sort(a,a+10);  //默认排序为升序,a为首地址,a+10为尾地址

 for(int i=0;i<10;i++)

 cout<<a[i]<<endl;

 return 0;

}

(2)自定义排序方式

bool compare(int a,int b)

{

 return a>b;

}

这就是告诉程序要实现从大到小的排序的方法!

#include<iostream>

#include<algorithm>

using namespace std;

bool complare(int a,int b)

{

 return a>b;

}

int main()

{

 int a[10]={9,6,3,8,5,2,7,4,1,0};

 for(int i=0;i<10;i++)

 cout<<a[i]<<endl;

 sort(a,a+10,compare);//在这里就不需要对compare函数传入参数了,//这是规则

 for(int i=0;i<10;i++)

 cout<<a[i]<<endl;

 return 0;

}

(3)容器vector排序  (string类似用迭代器进行)

#include<vector>
#include<string>
#include <iostream>
#include <algorithm>
using namespace std;


int my_cmp(pair<string,int> p1,pair<string,int>  p2)
{
return p1.second > p2.second;
}
int main(int argc,char* argv)
{
vector<pair<string,int> > m_vector;

m_vector.push_back(make_pair("a",1));
m_vector.push_back(make_pair("c",3));
m_vector.push_back(make_pair("b",2));
sort(m_vector.begin(),m_vector.end(),my_cmp);
cout << m_vector[0].first<< "  " << m_vector[1].first << "  " << m_vector[2].first << std::endl;
}
这是从大到小进行排序的,输出是c,b,a.


猜你喜欢

转载自blog.csdn.net/z13724549107/article/details/77647534