返回最大值
1. C++20
C++20 引入了 std::max
的 constexpr
版本,以及 std::ranges::max
,可以更方便地返回最大值。
1.1 示例
#include <iostream>
#include <algorithm> // std::max
#include <vector>
#include <ranges> // std::ranges::max
int main() {
// 使用 std::max
constexpr int a = 10;
constexpr int b = 20;
constexpr int max_value = std::max(a, b); // constexpr 保证编译时求值
std::cout << "Max of a and b: " << max_value << std::endl;
// 使用 std::ranges::max
std::vector<int> nums = {5, 2, 8, 1, 9};
auto max_element = std::ranges::max(nums);
std::cout << "Max element in nums: " << max_element << std::endl;
return 0;
}
1.2 说明
std::max(a, b)
: 返回a
和b
中的较大值。std::ranges::max(range)
: 返回range
中的最大值。range
可以是任何支持迭代器的范围。- 如果
range
为空,则行为未定义。
2. C++11
在 C++11 中,可以使用 std::max
返回两个值中的最大值,或者结合 std::max_element
和容器的迭代器来找到容器中的最大值。
2.1 示例
#include <iostream>
#include <algorithm> // std::max, std::max_element
#include <vector>
int main() {
// 使用 std::max
int a = 10;
int b = 20;
int max_value = std::max(a, b);
std::cout << "Max of a and b: " << max_value << std::endl;
// 使用 std::max_element
std::vector<int> nums = {5, 2, 8, 1, 9};
auto max_element_it = std::max_element(nums.begin(), nums.end());
if (max_element_it != nums.end()) {
std::cout << "Max element in nums: " << *max_element_it << std::endl;
}
return 0;
}
2.2 说明
std::max(a, b)
: 返回a
和b
中的较大值。std::max_element(begin, end)
: 返回指向[begin, end)
范围内最大元素的迭代器。- 如果范围为空,则返回
end
。 - 需要通过解引用迭代器来获取最大值。
- 如果范围为空,则返回