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.

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

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) << '
';
 
    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

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