C ++中是否有任何预定义函数可以从给定数组中找到最小和最大元素?

Is there any predefined function in C++ to find the minimum and maximum element from a given array?

我有一个数组

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

我想用函数计算最小和最大元素,如果有的话?请帮忙

是的,有:std::minmax_element. There's also std::max_element for finding just the max and 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)));
}