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
- 参考