C++之STL(五)

1、算法

2、算法分类

3、非变动性算法

4、变动性算法

5、移除性算法

6、变序性算法

7、排序算法

8、已序区间算法

9、数值算法

10、算法尾词

11、非变动性算法示例

在使用的时候,会拷贝一份出来,所以不会对原数据有影响。主要是要点进去看内部源码的实现。

cpp 复制代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

void print_element(int n)
{
    cout << n << ' ';
}

bool bigger_than_4(int n)
{
    return n > 4;
}
int main() {
    int a[] = {1, 2, 3, 4, 5};
    vector<int> v(a, a+5);

    vector<int>::const_iterator it;
    for(it = v.begin(); it != v.end(); ++it)
    {
        cout << *it << ' ';
    }
    cout << endl;

    // 这个其实就是用for循环遍历,然后把每次遍历的元素当作参数传给print_element去执行
    // 所以print_element中参数的类型要和v的类型一致
    for_each(v.begin(), v.end(), print_element);
    cout << endl;


    it = min_element(v.begin(), v.end());
    if (it != v.end())
    {
        cout << *it << endl;
    }

    it = max_element(v.begin(), v.end());
    if (it != v.end())
    {
        cout << *it << endl;
    }

    it = find(v.begin(), v.end(), 4);
    if (it != v.end())
    {
        cout << it - v.begin() << endl;
    }
    else
    {
        cout << "not found" << endl;
    }

    it = find_if(v.begin(), v.end(), bigger_than_4);
    if (it != v.end())
    {
        cout << it - v.begin() << endl;
    }
    else
    {
        cout << "not found" << endl;
    }
    return 0;
}
// 输出
1 2 3 4 5
1 2 3 4 5
1
5
3
4
相关推荐
C++ 老炮儿的技术栈19 分钟前
什么是函数重载?为什么 C 不支持函数重载,而 C++能支持函数重载?
c语言·开发语言·c++·qt·算法
猪八戒1.037 分钟前
C++ 回调函数和Lambda表达式
c++
源远流长jerry1 小时前
匿名函数lambda、STL与正则表达式
c++
tan180°2 小时前
Linux进程信号处理(26)
linux·c++·vscode·后端·信号处理
一只鱼^_2 小时前
牛客练习赛138(首篇万字题解???)
数据结构·c++·算法·贪心算法·动态规划·广度优先·图搜索算法
李匠20243 小时前
C++GO语言微服务之Dockerfile && docker-compose②
c++·容器
2301_803554523 小时前
c++和c的不同
java·c语言·c++
Darkwanderor3 小时前
c++STL-通用(反向)迭代器适配器
c++
Magnum Lehar4 小时前
3d游戏引擎的Utilities模块实现
c++·算法·游戏引擎
青瓦梦滋4 小时前
【语法】C++的多态
开发语言·c++