首页 > 解决方案 > C++ 中是否有任何预定义函数可以从给定数组中查找最小和最大元素?

问题描述

我有一个数组

double weights[]={203.21, 17.24, 125.32, 96.167}

如果有的话,我希望通过使用函数来计算最小和最大元素?请帮忙

标签: c++functionminimum

解决方案


是的,有:std::minmax_element。还有 用于查找最大值的std::max_element用于查找最小值的 std::min_element。


应用于您的代码:

#include <algorithm>
#include <iterator>

int main() {

  double weights[]={203.21, 17.24, 125.32, 96.167};

  auto minMaxIterators = std::minmax_element(std::begin(weights), std::end(weights));

  // minMaxIterators is a pair of iterators. To find the actual doubles
  // themselves, we have to separate out the pair and then dereference.
  double minWeight = *(minMaxIterators.first);
  double maxWeight = *(minMaxIterators.second);

  // Alternately, using structured bindings to extract elements from the pair
  auto [minIt, maxIt] = std::minmax_element(std::begin(weights), std::end(weights));
  minWeight = *minIt;
  maxWeight = *maxIt;

  // Alternately, using min_element and max_element separately
  minWeight = *(std::min_element(std::begin(weights), std::end(weights)));
  maxWeight = *(std::max_element(std::begin(weights), std::end(weights)));
}

推荐阅读