Search code examples
c++functionminimum

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


I have an array

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

I wish to calculate the minimum and maximum element by using a function if there's any? Please help


Solution

  • Yes, there is: std::minmax_element. There's also std::max_element for finding just the max and std::min_element for finding just the min.


    As applied to your code:

    #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)));
    }