min and max functions in c++

Included in the header file <algorithm> in the C++ standard library, the min and max macros are defined in the header file <windows.h>. If <algorithm> is included while <windows.h> is included, the function will not be available.

<windows.h> provides functions such as _cpp_min to replace the min function.

C++11 Standard: The prototype of the min function in <algorithm>

default (1)
template <class T> const T& min (const T& a, const T& b);
custom (2)
template <class T, class Compare>
  const T& min (const T& a, const T& b, Compare comp);
initializer list (3)
template <class T> T min (initializer_list<T> il);
template <class T, class Compare>
  T min (initializer_list<T> il, Compare comp);

Return the smallest
Returns the smallest of  a and  b. If both are equivalent,  a is returned.

The versions for  initializer lists (3) return the smallest of all the elements in the list. Returning the first of them if these are more than one.

The function uses  operator< (or  comp, if provided) to compare the values.
eg:custom2<pre style="margin-top: 0px; margin-bottom: 0px; color: rgb(0, 128, 0);">template <class T, class Compare>
  const T& min (const T& a, const T& b, Compare comp);
 
 
#include<iostream>
#include<algorithm>
using namespace std;
struct var {
	char *name;
	int key;
	var(char *a,int k):name(a),key(k){}
};
bool comp(const var& l, const var& r) {
	return l.key < r.key;
}
int main() {
	var v1("var1", 2);
	var v2("var2", 3);
	cout << std::min(v1, v2,comp).name << endl;
	return 0;
}
stable_sort, max function is the same as min

Guess you like

Origin blog.csdn.net/u013349653/article/details/51136945