std::minmax() and std::minmax_element() in C++ STL
C++ defined functions to get smallest and largest elements among 2 or in a container using different functions. But there are also functions that are used to get both smallest and largest element using a single function, “minmax()” function achieves this task for us. This function is defined in “algorithm” header file. This article would deal in its implementation and other related functions.
- minmax(a, b): This function returns a pair, in which 1st element is of minimum of the two elements and the 2nd element is maximum of 2 elements.
- minmax(array of elements): This function returns similarly as 1st version. Only difference is that in this version, the accepted argument is a list of integers/strings among which maximum and minimum are obtained. Useful in cases when we need to find maximum and minimum elements in list without sorting.
The minimum value obtained is : 23 The maximum value obtained is : 53 The minimum value obtained is : 1 The maximum value obtained is : 6
Time Complexity: O(n) where n is the number of elements from which we have to find the minimum and maximum element.
Auxiliary Space: O(1)
- minmax_element(): This purpose of this function is same as above functions i.e to find minimum and maximum element. But it differs in return type and accepted argument. This function accepts start and end pointer as its argument and is used to find maximum and minimum element in a range. This function returns pair pointer, whose 1st element points to the position of minimum element in the range and 2nd element points to the position of maximum element in the range. If there are more than 1 minimum numbers, then the 1st element points to first occurring element. If there are more than 1 maximum numbers, then the 2nd element points to last occurring element.
The minimum value position obtained is : 1 The maximum value position obtained is : 0 The minimum value position obtained is : 1 The maximum value position obtained is : 5
Time Complexity: O(n)
Auxiliary Space: O(1)
This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Please Login to comment...