Loading... ## algorithm头文件下常用函数 ### max(),min(),abs() max(x,y)和min(x,y)分别返回x和y中的最大值和最小值,且参数必须是两个。 abs(x) 返回x的绝对值。x必须为整数,浮点型的绝对值要用math头文件下的fabs #### 代码实例: ```cpp #include<cstdio> #include<algorithm> using namespace std; int main() { int a = -5, b = 10; printf("%d %d\n", max(a, b), min(a, b)); printf("%d", abs(a)); return 0; } ``` ### swap() swap(x,y)用来交换x和y的值 #### 代码实例: ```cpp #include<cstdio> #include<algorithm> using namespace std; int main() { int a = 5, b = 10; swap(a, b); printf("%d %d", a, b); return 0; } ``` ### reverse() reverse(it,it2) 可以将数组指针在[it,it2)之间的元素或容器的迭代器在[it,it2)范围内的元素进行反转。 #### 代码实例: ```cpp #include<cstdio> #include<algorithm> using namespace std; int main() { int a[10]={10,11,12,13,14,15}; reverse(a,a+6); for(int i=0;i<6;i++){ printf("%d ",a[i]); } return 0; } ``` ### next_permutation() next_permutation() 给出一个序列在全排列中的下一个序列 #### 代码实例: ```cpp #include<cstdio> #include<string> #include<algorithm> using namespace std; int main() { int a[10]={1,2,3}; do{ printf("%d %d %d\n",a[0],a[1],a[2]); }while(next_permutation(a,a+3)); return 0; } ``` ### fill() fill() 可以把数组或容器中的某一段区间赋为某个相同的值。和memset不同,这里的赋值可以使数组类型对应范围中的任意值。 #### 代码实例: ```cpp #include<cstdio> #include<string> #include<algorithm> using namespace std; int main() { int a[10]={1,2,3,4,5}; fill(a,a+5,233); for(int i=0;i<5;i++){ printf("%d ",a[i]); } return 0; } ``` 最后修改:2021 年 08 月 28 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 如果文章有用,请随意打赏。