STL—algorithm(1)

简介: 在algorithm中,有很多函数,这些函数是已经写好的,可以直接调用,十分的方便,可以精简代码量辅助我们思考在使用algorithm的函数之前需要添加头文件#include <algorithm>

文章目录

一、algorithm

二、常用函数一览

1.max(), min()

2.abs()

3.swap()

4.reverse()

5.fill()


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


目录
相关文章
|
5月前
|
算法 搜索推荐 大数据
算法(Algorithm)
算法(Algorithm)
85 0
|
5月前
|
机器学习/深度学习 算法 程序员
C++ Algorithm 库 算法秘境探索(Algorithm Wonderland Exploration)
C++ Algorithm 库 算法秘境探索(Algorithm Wonderland Exploration)
186 1
|
12月前
|
算法 C++
【Hello Algorithm】基础数据结构
【Hello Algorithm】基础数据结构
41 0
|
3月前
|
传感器
Algorithm
【7月更文挑战第22天】
41 0
|
5月前
|
Go
Sereja and Algorithm
Sereja and Algorithm
31 0
|
5月前
|
算法
Aho Corasick Algorithm
Aho Corasick Algorithm
41 0
|
5月前
|
存储 C++ 索引
C++:STL - vector
C++:STL - vector
65 1
|
算法 搜索推荐 程序员
Euclidean algorithm
数论算法是研究整数及其性质的算法。数论算法在密码学、编码、计算机科学和其他领域中有广泛的应用。以下是数论算法的一些常见的算法以及它们的实现方法和示例代码:
82 1
|
算法 C++ 容器
STL之vector
STL之vector
|
C++ 容器
STL—algorithm(2)(上)
在algorithm中,有很多函数,这些函数是已经写好的,可以直接调用,十分的方便,可以精简代码量辅助我们思考 在使用algorithm的函数之前需要添加头文件#include <algorithm>
88 0