std min element

suggest change
template <class ForwardIterator>
ForwardIterator min_element (ForwardIterator first, ForwardIterator last);

template <class ForwardIterator, class Compare>
ForwardIterator min_element (ForwardIterator first, ForwardIterator last,Compare comp);

Effects

Finds the minimum element in a range

Parameters

first - iterator pointing to the beginning of the range

last - iterator pointing to the end of the range comp - a function pointer or function object that takes two arguments and returns true or false indicating whether argument is less than argument 2. This function should not modify inputs

Return

Iterator to the minimum element in the range. If the range is empty, returns last. Dereferencing that iterator is undefined.

Complexity

Exactly max(N - 1, 0) comparisons, where N is the number of elements.

Example

The example uses std::ranges::min_element (C++20), a projection, and C++17 class template argument deduction for std::vector.

#include <algorithm>
#include <iostream>
#include <string>
#include <utility>
#include <vector>

int main() {
  
  const std::vector intVec{30, 200, 167, 56, 75, 94, 10, 73, 52, 6, 39, 43};
  
  const std::vector<std::pair<std::string, int>> pairVector{
      {"y", 25}, {"b", 2}, {"z", 26}, {"e", 5}};
  
  
  // default using < operator
  const auto minInt = std::ranges::min_element(intVec);
  
  // Use a projection to compare the second member of each pair.
  const auto minPair = std::ranges::min_element(pairVector, {}, &std::pair<std::string, int>::second);
  
  
  //print minimum of intVector
  std::cout << "min int from default: " << *minInt << '\n';
  
  //print minimum of pairVector
  std::cout << "min pair by second: " << minPair->second << '\n';
}
min int from default: 6
min pair by second: 2

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents