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
相关推荐
南境十里·墨染春水40 分钟前
C++笔记 继承关系中构造和析构顺序(面向对象)
开发语言·c++·笔记
是娇娇公主~1 小时前
详解布隆过滤器
c++
m0_716765231 小时前
C++巩固案例--通讯录管理系统详解
java·开发语言·c++·经验分享·学习·青少年编程·visual studio
G果1 小时前
ros2工程 debug(vscode)
c++·ide·vscode·编辑器·bug·debug·ros2
jf加菲猫1 小时前
第10章 数据处理
xml·开发语言·数据库·c++·qt·ui
楼田莉子1 小时前
序列化与反序列化及其ProtoBuf学习总结
开发语言·网络·c++·后端·学习
wengqidaifeng1 小时前
备战蓝桥杯----C/C++组 (三)算法讲解前言
c语言·c++·蓝桥杯
森G2 小时前
30、QStandardItemModel 和 QTableView---------Model/View模型视图
c++·qt
maxmaxma2 小时前
ROS2机器人少年创客营:Python第二课
c++·python·机器人
山栀shanzhi2 小时前
FFmpeg 实战:RGB 裸流编码成 MP4,全流程详解(含源码
c++·ffmpeg