如果我们需要对一个数组或者向量进行排序,我们可以使用stl库里自带的函数来完成,就不需要自己手写排序了。
排序函数包含在头文件#include<algorithm>里面
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main()
{
const int N = 5;
int a[N] = {2,5,3,1,4};
sort(a , a+N); //使用排序函数,区间是左闭右开 也就是说对a[0]...a[N-1]排序
for(int i = 0 ; i < N ; ++i)
{
cout << a[i] << " ";
}
cout<<endl;
sort(a , a + N , greater<int>() ); //使用函数对象,可以对数组进行逆序排序
for(int i = 0 ; i < N ; ++i)
{
cout << a[i] << " ";
}
cout<<endl;
//我们也可以对字符串使用sort函数进行排序
string b[N] = {"www","algorithm","racer","text","wait"};
sort(b , b+N); //这样可以对字符串按字典序排序
for(int i = 0 ; i < N ; ++i)
{
cout << b[i] << " ";
}
cout<<endl;
//如果想要逆序排序,和上面的代码类似
sort(b , b+N , greater<int>());
//可以对vector使用sort函数进行排序
vector<string> v = {"www","algorithm","racer","text","wait"};
sort(v.begin , v.end());
//逆序也可以和上面类似:
sort(v.begin , v.end() , greater<int>());
//输出向量中的内容,使用迭代器:
for(auto iter = v.begin() ; iter != v.end() ; ++iter)
{
cout<< *iter <<endl;
}
//还可以使用一种方式对向量进行逆序排序:
sort(v.rbegin() , v.rend());
}
CNSDDYU6%5D%7DCFJ%25T.png)
基于范围的for循环:
for(const string & x : v) //使用常量引用!
cout << x << endl; //正向输出vector之中的内容






Comments NOTHING