一.sort函数包含在头文件为#include<algorithm>的c++标准库中;
二.sort函数的模板有三个参数:
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
第一个参数为排序的起始地址;
第二个参数为排序的结束地址;
第三个参数为排序的方式;
实例
#include<iostream>
#include<algorithm>
using namespace std;
main()
{
int a[5]={45,12,34,77,90};
sort(a,a+5);
for(int i=0;i<5;i++)
{
cout<<a[i]<<" ";
}
return 0;
}
也可以使用自定义排序
Like this:题目背景
#include <bits/stdc++.h>
using namespace std;
struct st
{
string str;
int t;
}a[114];
bool comp(st a,st b)
{
return a.t<b.t;
}
int main()
{
int n,k;
cin>>n>>k;
for(int i=1;i<=n;i++)
{
cin>>a[i].str>>a[i].t;
}
sort(a+1,a+n+1,comp);
cout<<a[k].str;
return 0;
}

本文详细介绍了C++标准库中的sort函数,包括其包含的头文件、模板参数(起始地址、结束地址和比较函数)、以及两个实例演示,分别展示了如何对整数数组和结构体进行排序。自定义排序函数的使用也被深入讲解。

2706

被折叠的 条评论
为什么被折叠?



