STL—algorithm(1)

举报
辰chen 发表于 2022/06/15 00:45:47 2022/06/15
【摘要】 文章目录 一、algorithm二、常用函数一览1.max(), min()2.abs()3.swap()4.reverse()5.fill() 一、algorithm 在algo...


一、algorithm

algorithm中,有很多函数,这些函数是已经写好的,可以直接调用,十分的方便,可以精简代码量辅助我们思考

在使用algorithm的函数之前需要添加头文件#include <algorithm>

由于algorithm下的函数有很多,这里分为两篇博客去介绍,第二篇博客见:STL—algorithm(2)


二、常用函数一览

1.max(), min()

max(x, y);min(x, y);分别返回x和y中的最大值和最小值,且参数必须是两个(可以是浮点数),如果想要返回三个数x, y, z的最大值可以采用max(x, max(y, z))的写法

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    int x = 3, y = 4;
    cout << max(x, y) << endl;
    
    double w = -2, v = 8;
    cout << min(w, v);
    
    return 0;
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

输出结果为:
4
-2

2.abs()

abs(x);返回的是x的绝对值,这里注意x必须是整数,浮点型的绝对值请使用#include <cmath>中的fabs

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    int x = -3;
    
    cout << abs(x);
    
    return 0;
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

输出结果为:3

3.swap()

swap(x, y);用来交换x和y的值

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    int x = 2, y = 3;
    
    cout << x << ' ' << y << endl;
    
    swap(x, y);
    
    cout << x << ' ' << y;
    
    return 0;
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

输出结果:
2 3
3 2

4.reverse()

reverse(it, it2);可以将数组指针在[it, it2)之间的元素或容器的迭代器在[it, it2)范围内的元素进行反转

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    int a[10];
    
    for (int i = 0; i < 10; i ++ ) a[i] = i + 1;
    
    reverse(a, a + 7);
    //把a[0] ~ a[6]进行反转
    for (int i = 0; i < 10; i ++ ) cout << a[i] << ' ';
    
    return 0;
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

输出结果为:7 6 5 4 3 2 1 8 9 10

5.fill()

fill()可以把数组或容器中的某一段区间赋值为某个相同的值,和memset不同,这里的赋值可以是数组类型对应范围中的任意值

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    int a[10];
    
    for (int i = 0; i < 10; i ++ ) a[i] = i;
    
    fill(a, a + 5, 666);
    
    for (int i = 0; i < 10; i ++ ) cout << a[i] << ' ';
    
    return 0;
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

输出结果为:666 666 666 666 666 5 6 7 8 9

文章来源: chen-ac.blog.csdn.net,作者:辰chen,版权归原作者所有,如需转载,请联系作者。

原文链接:chen-ac.blog.csdn.net/article/details/116402927

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。