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
相关推荐
Thera7771 小时前
状态机(State Machine)详解:原理、优缺点与 C++ 实战示例
开发语言·c++
linux开发之路1 小时前
C++高性能日志库开发实践
c++·c++项目·后端开发·c++新特性·c++校招
刻BITTER2 小时前
在TRAE 上安装PlatformIO
c++·单片机·嵌入式硬件·arduino
永远都不秃头的程序员(互关)2 小时前
C++动态数组实战:从手写到vector优化
c++·算法
水力魔方3 小时前
武理排水管网模拟分析系统应用专题5:模型克隆与并行计算
数据库·c++·算法·swmm
OliverH-yishuihan3 小时前
在win10上借助WSL用VS2019开发跨平台项目实例
linux·c++·windows
汉克老师4 小时前
GESP2025年12月认证C++二级真题与解析(编程题1 (环保能量球))
c++·gesp二级·gesp2级
郝学胜-神的一滴4 小时前
Linux进程与线程控制原语对比:双刃出鞘,各显锋芒
linux·服务器·开发语言·数据结构·c++·程序人生
青岛少儿编程-王老师5 小时前
CCF编程能力等级认证GESP—C++2级—20251227
java·开发语言·c++
javachen__5 小时前
341-十道经典程序设计题目
数据结构·c++·算法