返回最大值(cpp 11 & 20)

返回最大值

1. C++20

C++20 引入了 std::maxconstexpr 版本,以及 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): 返回 ab 中的较大值。
  • 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): 返回 ab 中的较大值。
  • std::max_element(begin, end): 返回指向 [begin, end) 范围内最大元素的迭代器。
    • 如果范围为空,则返回 end
    • 需要通过解引用迭代器来获取最大值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值