c++中min和max函数

包含在c++标准库中头文件<algorithm>中,在头文件<windows.h>中定义了min,max的宏,若在包含<algorithm>的同时包含<windows.h>会导致函数无法使用。

<windows.h>提供了_cpp_min等函数来代替min函数的功能。

C++11标准:<algorithm>中min函数的原型

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函数同min

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值