最值查找max,min及类似函数用法与说明

本文详细介绍了在算法竞赛中常用的max,min函数的基础用法,以及max_element,min_element和nth_element函数的用法和示例,帮助读者理解这些函数在寻找和排序中的应用。
摘要由CSDN通过智能技术生成

本篇介绍了在算法竞赛中最为常用的关于最值查找的部分函数


一、max和min函数的基本用法

max(a, b)返回a和b中较大的那个值,只能传入两个值,或传入一个列表。

传入两个值

#include<iostream>
#include<algorithm>

using namespace std;

int main()
{
    int a, b;
    cin >> a >> b; //输入两个数a和b
    
    cout << max(a, b) << endl;//打印最大值
    
    return 0;
}

传入一个列表

#include<iostream>
#include<algorithm>

using namespace std;

int main()
{
    cout << max({2, 4, 7, 9, 21}) << endl; //打印输出21
    
    return 0;
}

同理,min(a, b)返回a和b中较小的那个值,只能传入两个值,或传入一个列表。

传入两个值

#include<iostream>
#include<algorithm>

using namespace std;

int main()
{
    int a, b;
    cin >> a >> b; //输入两个数a和b
    
    cout << min(a, b) << endl;//打印最大值
    
    return 0;
}

传入一个列表

#include<iostream>
#include<algorithm>

using namespace std;

int main()
{
    cout << min({2, 4, 7, 9, 21}) << endl; //打印输出2
    
    return 0;
}

二、max_element和min_element函数用法及说明

max_element的用法
max_element(st, ed)返回地址[st, ed)中最大的那个值的地址(迭代器), 传入参数为两个地址或迭代器。

#include<iostream>
#include<algorithm>
#include<vector>

using namespace std;

vector<int> arr = {2, 5, 7, 3, 4}; //这里可以使用容器,也可以使用数组

int main()
{
    cout << *max_element(arr.begin(), arr.end()) << endl; //输出最大元素7,通过*来解引用得到地址的值
    
    return 0;
}

min_element的用法
min_element(st, ed)返回地址[st, ed)中最小的那个值的地址(迭代器), 传入参数为两个地址或迭代器。

#include<iostream>
#include<algorithm>
#include<vector>

using namespace std;

vector<int> arr = {2, 5, 7, 3, 4}; //这里可以使用容器,也可以使用数组

int main()
{
    cout << *min_element(arr.begin(), arr.end()) << endl; //输出最小元素2,通过*来解引用得到地址的值
    
    return 0;
}

三、nth_element函数的基本用法

nth_element函数属于一种排序函数,是一种特殊的部分排序逻辑。其用法为:
nth_element(st, k, ed)返回值为void, 传入参数为三个地址或迭代器。其中第二个参数位置的元素将处于正确的位置,其他位置的元素顺序可能是任意的,但前面的都比它小,后面的都比它大。

#include<iostream>
#include<algorithm>
#include <vector>

using namespace std;

vector<int> arr = {4, 2, 5, 8, 3, 7, 9};

int main()
{
    nth_element(arr.begin(), arr.begin() + 3, arr.end());
    
    for(int i = 0; i < arr.size(); i ++)
        cout << arr[i] << " ";
        
    return 0;
}

代码结果:
在这里插入图片描述

这是最值查找的全部内容了,之后有了更深入的学习后会进行进一步完善和修改。觉得这篇文章对您有帮助的可以点一个赞,这是对我最大的支持和动力。

  • 12
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Pigwantofly

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值