c++的sort函数

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.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;
}

拜拜!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值