6.9 algorithm 头文件下的常用函数
使用algorithm头文件
6.9.1 max()、min()和abs()
max(x, y)和min(x, y)分别返回x和y中的最大值和最小值
abs(x)返回x的绝对值,注意浮点型的绝对值请用math头文件下的fabs函数
6.9.2 swap()
swap(x, y)用来交换x和y的值
6.9.3 reverse()
reverse(it, it2)可以将数组指针在[it, it2)之间的元素或容器的迭代器在[it, it2)范围内的元素进行反转
#include <bits/stdc++.h>
#include <algorithm>
using namespace std;
int main(){
int a[10] = {10, 11, 12, 13, 14, 15};
reverse(a, a+4);
for(int i = 0; i < 6; i++){
cout<<a[i]<<' ';
}
return 0;
}
输出结果:
13 12 11 10 14 15
6.9.4 next_permutation()
next_permutation()给出一个序列在全排列中的下一个序列
6.9.5 fill()
fill()可以把数组或容器中的某一段区间赋为某个区间相同的值
6.9.6 sort()
sort用来排序的函数
sort(首元素地址, 尾元素地址的下一个地址, 比较函数)
前两个参数是必填项,第三个可根须需要填写
#include <bits/stdc++.h>
#include <algorithm>
using namespace std;
int main(){
int a[6] = {9, 4, 2, 5, 6, -1};
sort(a, a+3);
for(int i = 0; i < 6; i++){
cout<<a[i]<<' ';
}
cout<<endl;
sort(a, a+6);
for(int i = 0; i < 6; i++){
cout<<a[i]<<' ';
}
return 0;
}
输出结果:
2 4 5 9 6 -1
-1 2 4 5 6 9
**第三个参数:**如何实现比较函数cmp?
#include <bits/stdc++.h>
#include <algorithm>
using namespace std;
bool cmp(int a, int b){
return a>b;
}
int main(){
int a[6] = {9, 4, 2, 5, 6, -1};
sort(a, a+4, cmp);
for(int i = 0; i < 6; i++){
cout<<a[i]<<' ';
}
cout<<endl;
sort(a, a+6, cmp);
for(int i = 0; i < 6; i++){
cout<<a[i]<<' ';
}
return 0;
}
输出结果:
9 5 4 2 6 -1
9 6 5 4 2 -1
6.9.7 lower_bound()和upper_bound()
lower_bound(first, last, val)用来寻找在数组或容器的[first,last)范围内第一个值大于等于val的元素的位置,如果是数组,则返回该位置的指针,如果是容器则返回该位置的迭代器
upper_bound(first, last, val)用来寻找在数组或容器的[first,last)范围内第一个值大于val的元素的位置,如果是数组,则返回该位置的指针,如果是容器则返回该位置的迭代器
如果数组或容器中没有需要寻找的元素,则lower_bound()和upper_bound()均返回可以插入该元素的位置的指针或迭代器