STL介绍2:algorithm头文件下的常用函数

一、max()、min()、abs()和swap()

#include
#include
using namespace std;
int main(){
	int a = 2, b = -3;
	cout << "MAX:" << max(a,b) << ' ' << "MIN:" << min(a,b) <<'\n';
	swap(a,b);
	cout << "交换a和b的值a= " << a << ' ' << "b=" << b << '\n';  
	cout << "b的绝对值:" << abs(b) << '\n';
	return 0;
}

二、sort():排序

sort(首元素地址,尾元素地址的下一位,比较函数)

#include
#include
using namespace std;
bool cmp(int a, int b){
	return a > b; // 当a>b的时候让a排在b的前面 
} 
int main(){
	int a[5] = {2, 3, 1, 7, 8};
	sort(a, a+5);
	for(int i = 0; i < 5; i++){
		cout << a[i] << ' ';
	}
	return 0;
}

你可能感兴趣的:(c++,算法,开发语言)