STL—algorithm(1)


一、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;
}

输出结果为:
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;
}

输出结果为: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;
}

输出结果:
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;
}

输出结果为: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;
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

辰chen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值