How to find the maximum and minimum values in a sequence? - Use STL's max_element() and min_element()

Suppose there is a sequence now, how do we find the minimum and maximum values ​​in this sequence? As the title says, STL provides algorithms to help us solve this problem. Below we describe both algorithms.

min_element() 

InputIterator
min_element(InputIterator beg,InputIterator end)

InputIterator
min_element(InputIterator beg,InputIterator end,CompFunc op)

max_element() 

InputIterator
max_element(InputIterator beg,InputIterator end)

InputIterator
max_element(InputIterator beg,InputIterator end,CompFunc op)
  • All algorithms return the position of the smallest or largest element in the interval [beg,end)
  • For the version without op parameter, operator<< is used to compare elements by default
  • op is used to compare two elements: op(elem1, elem2), if the first element is smaller than the second element, it should return true
  • If there are multiple min or max values, the above algorithm returns the first min or max value found
  • op should not modify the passed parameters

Let's take a look at the program, find the minimum and maximum elements in col, and output the absolute values ​​of the minimum and maximum elements through absLess()

#include<cstdlib>
#include"algostuff.h"
using namespace std;

bool absLess(int elem1, int elem2)
{
	return abs(elem1) < abs(elem2);
}
int main()
{
	deque<int> col;
	INSERT_ELEMENTS(col, 2, 8);
	INSERT_ELEMENTS(col, -3, 5);

	PRINT_ELEMENTS(col); //2 3 4 5 6 7 8 -3 -2 -1 0 1 2 3 4 5

	//process and print minimum and maximum

	cout << "minimum: " << *min_element(col.begin(), col.end()) << endl; 
	//minimum: -3
	cout << "maximum: " << *max_element(col.begin(), col.end()) << endl;
	//maximum: 8

	//process and print minimum and maximum of absolute values

	cout << "minimum of absolute values: "
		<< *min_element(col.begin(), col.end(), absLess) << endl;
	//minimum of absolute values: 0

	cout << "maximum of absolute values: "
		<< *max_element(col.begin(), col.end(), absLess) << endl;
	//maximum of absolute values: 8
}

algostuff.h 

 It should be noted that these two algorithms return the position of the largest and smallest element respectively, so to output the corresponding value, the unary operator operator* must be used to print its value.

Guess you like

Origin blog.csdn.net/yangSHU21/article/details/130536812