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
相关推荐
Yu_Lijing2 分钟前
基于C++的《Head First设计模式》笔记——状态模式
c++·笔记·设计模式
顶点多余16 分钟前
静态链接 vs 动态链接,静态库 vs 动态库
linux·c++·算法
AI视觉网奇20 分钟前
ue5 开发 web socket server 实战2026
c++·学习·ue5
王老师青少年编程1 小时前
2024年3月GESP真题及题解(C++八级): 接竹竿
c++·题解·真题·gesp·csp·八级·接竹竿
偷星星的贼111 小时前
C++中的访问者模式实战
开发语言·c++·算法
雾岛听蓝1 小时前
红黑树深度解析:设计原理与实现逻辑
c++
gjxDaniel1 小时前
A+B问题天堂版
c++·算法·字符串·字符数组
M__331 小时前
动态规划进阶:简单多状态模型
c++·算法·动态规划
米优1 小时前
使用Qt实现消息队列中间件动态库封装
c++·中间件·rabbitmq
N.D.A.K2 小时前
CF2138C-Maple and Tree Beauty
c++·算法