Tuesday, November 21, 2017

C++17: std::minmax_element()

C++17 added the algorithm std::minmax_element(), which returns iterators to both the first maximum value and the first minimum value over a range. Here is an example:

#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
  std::vector<int> myVector{3, 1, 4, 1, 5, 9, 2, 6, 5};
  std::pair<std::vector<int>::iterator, std::vector<int>::iterator> minmax;

  minmax = std::minmax_element(myVector.begin(), myVector.end());

  std::cout << *minmax.first  << " "; // 1
  std::cout << *minmax.second << " "; // 9

  std::cout << std::endl;
  return 0;
}
// Output: 1 9
Reference: http://en.cppreference.com/w/cpp/algorithm/minmax_element

No comments:

Post a Comment