Tuesday, November 21, 2017

C++17: std::max_element() and std::min_element()

C++17 added the algorithms std::max_element() and std::min_element(), which return iterators to the first maximum or minimum value, respectively, 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::cout<<*(std::max_element(myVector.begin(),myVector.end()))<<" ";//9
  std::cout<<*(std::min_element(myVector.begin(),myVector.end()))<<" ";//1
  std::cout<<std::endl;
  return 0;
}
// Output: 9 1
References:
http://en.cppreference.com/w/cpp/algorithm/max_element
http://en.cppreference.com/w/cpp/algorithm/min_element

No comments:

Post a Comment