首页 > 编程语言 > 详细

C++之max和max_element

时间:2018-12-24 21:49:49      阅读:268      评论:0      收藏:0      [点我收藏+]

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.

#include <algorithm>
#include <iostream>
#include <string>
 
int main()
{
    std::cout << "larger of 1 and 9999: " << std::max(1, 9999) << '\n'
              << "larger of 'a', and 'b': " << std::max('a', 'b') << '\n'
              << "longest of \"foo\", \"bar\", and \"hello\": " <<
                  std::max( { "foo", "bar", "hello" },
                            [](const std::string& s1, const std::string& s2) {
                                 return s1.size() < s2.size();
                             }) << '\n';
}

output

larger of 1 and 9999: 9999
larger of 'a', and 'b': b
longest 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.

#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
 
static bool abs_compare(int a, int b)
{
    return (std::abs(a) < std::abs(b));
}
 
int main()
{
    std::vector<int> v{ 3, 1, -14, 1, 5, 9 }; 
    std::vector<int>::iterator result;
 
    result = std::max_element(v.begin(), v.end());
    std::cout << "max element at: " << std::distance(v.begin(), result) << '\n';
 
    result = std::max_element(v.begin(), v.end(), abs_compare);
    std::cout << "max element (absolute) at: " << std::distance(v.begin(), result);
}

output

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

同理:min 和min_element

  • 参考

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

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

C++之max和max_element

原文:https://www.cnblogs.com/ChrisCoder/p/10171134.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!