C++之max和max_element

C++之max和max_element

std::max()

Returns the greater of a and b, or the values in initializer list ilist 。it can use operator< to compare the value, or use the given comparison function comp.

1#include <algorithm> 2#include <iostream> 3#include <string> 4 5int main() 6{ 7 std::cout << "larger of 1 and 9999: " << std::max(1, 9999) << '\n' 8 << "larger of 'a', and 'b': " << std::max('a', 'b') << '\n' 9 << "longest of \"foo\", \"bar\", and \"hello\": " << 10 std::max( { "foo", "bar", "hello" }, 11 [](const std::string& s1, const std::string& s2) { 12 return s1.size() < s2.size(); 13 }) << '\n'; 14}

output

1larger of 1 and 9999: 9999 2larger of 'a', and 'b': b 3longest of "foo", "bar", and "hello": hello

std::max_element()

Finds the greatest element in the range [first, last). it can use operator< to compare the value, or use the given comparison function comp.

1#include <algorithm> 2#include <iostream> 3#include <vector> 4#include <cmath> 5 6static bool abs_compare(int a, int b) 7{ 8 return (std::abs(a) < std::abs(b)); 9} 10 11int main() 12{ 13 std::vector<int> v{ 3, 1, -14, 1, 5, 9 }; 14 std::vector<int>::iterator result; 15 16 result = std::max_element(v.begin(), v.end()); 17 std::cout << "max element at: " << std::distance(v.begin(), result) << '\n'; 18 19 result = std::max_element(v.begin(), v.end(), abs_compare); 20 std::cout << "max element (absolute) at: " << std::distance(v.begin(), result); 21}

output

1max element at: 5 2max element (absolute) at: 2

同理:min 和min_element

  • 参考

https://en.cppreference.com/w/cpp/algorithm/max

https://en.cppreference.com/w/cpp/algorithm/max_element

点赞
收藏

评论区

加载中...

相关推荐

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

sqlserver根据条件生成插入语句

ALTERproc\dbo\.\proc\_insert\(@tablenamevarchar(256),@wherevarchar(max))asbeginsetnocountondeclare@sqlstrvarchar(MAX)declare@sqlstr1varchar(MAX)dec

oracle中的greatest 函数和 least函数

oracle中的greatest函数和least函数原文地址:https://blog.csdn.net/sinat\_32023305/article/details/78778596greatest(max(one),max(two),max(three))求多列的最大

udp之关于linux udp收发包缓冲区大小

1、修订单个socket的缓冲区大小:通过setsockopt使用SO\_RCVBUF来设置接收缓冲区,该参数在设置的时候不会与rmem\_max进行对比校验,但是如果设置的大小超过rmem\_max的话,则超过rmem\_max的部分不会生效;2、修订linux系统udp缓冲区大小:通过rmem\_max来设置系统中udp缓存的上限,该值可通过如下方

Flink 系例 之 MaxBy

maxBy聚合:获取一组数据流算子中最大的记录行(和max的区别,max是返回计算字段的最大值)示例环境java.version:1.8.xflink.version:1.11.1 示例数据源(项目码云下载)Flink系例之搭建开发环境与数据(https://my.oschina.net/u/437309