algorithm头文件的常用函数:
- max(x,y) ,min(x,y):返回x和y中的最大值和最小值,x和y可以是浮点型。abs(x)返回x的绝对值,x必须是整数
- swap(x,y) 交换x和y存储空间的值
- reverse(it1,it2) 将数组下标在[it1,it2)之间的元素或容器的迭代器在[it1,it2)之家的元素进行反转。
- next_permutation(it1,it2) 将[it1,it2)之间的元素组合转化为在元素按字典顺序进行排列组合顺序下一个组合,若有返回true,否则返回false。如[it1,it2)直接的元素为2,1,3,在按字典顺序所以排列组合为123,132,213,231,312,321,而213组合的下一个是231,所以返回true。如果想列出所有组合,就要保证[it1,it2)有字典顺序,即首先对其sort排序。
char a[10] = {'3','1','2','\0'};
while(next_permutation(a,a+3)){
cout << a << endl;
}
// 输出结果
312
321
// 想要输出所有排列组合,先对其排序,在输出当前排列后进行转换为下一个,所有用do-while循环
char a[10] = {'2','3','1','\0'};
sort(a,a+3); //
do{
cout << a << endl;
}while(next_permutation(a,a+3));
// 输出结果
123
132
213
231
312
321
- fill(it1,it2,x) 给[it1,it2)区间所有单元赋上对应数组或容器类型的x值,与memset不同,memset按字节赋值,只能是-1或0.
- sort(it1,it2,cmp(非必填)) 不写cmp比较函数,默认递增排序。通过改写cmp来实现基本类型,结构,容器排序。容器中只有vector,string,deque可以使用sort,而像set,map用红黑树是实现的,元素本身有序。
#include <iostream>
#include <algorithm>
const int max = 5;
struct Node
{
int data;
}node[max] = {{4},{5},{3},{1},{2}};
bool cmp1(double &a, double &b);
bool cmp2(Node &a, Node &b);
int main(){
using namespace std;
double num[10] = {2.1, 4, 6, 10, 27, 2.6, -1, 1, 7.8, 11};
sort(num,num+10,cmp1);
for(int i = 0; i < 10; i++){
cout << num[i] <<" ";
}
cout << endl;
sort(node,node+5,cmp2);
for(int i = 0; i < 5; i++){
cout << node[i].data <<" ";
}
}
bool cmp1(double &a, double &b){
return a > b;
}
bool cmp2(Node &a, Node &b){
return a.data > b.data;
}
// 输出结果
27 11 10 7.8 6 4 2.6 2.1 1 -1
5 4 3 2 1