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
相关推荐
ULTRA??21 小时前
各种排序算法时间复杂度分析和实现和优势
c++·python·算法·排序算法
博语小屋21 小时前
简单线程池实现(单例模式)
linux·开发语言·c++·单例模式
墨雪不会编程21 小时前
C++基础语法篇八 ——【类型转换、再探构造、友元】
java·开发语言·c++
yuuki2332331 天前
【C++】内存管理
java·c++·算法
刃神太酷啦1 天前
Linux 进程核心原理精讲:从体系结构到实战操作(含 fork / 状态 / 优先级)----《Hello Linux!》(6)
java·linux·运维·c语言·c++·算法·leetcode
一个不知名程序员www1 天前
算法学习入门---二叉树
c++·算法
小李小李快乐不已1 天前
数组&&矩阵理论基础
数据结构·c++·线性代数·算法·leetcode·矩阵
coderxiaohan1 天前
【C++】用哈希表封装unordered_map和unordered_set
开发语言·c++·散列表
福尔摩斯张1 天前
TCP协议深度解析:从报文格式到连接管理(超详细)
linux·c语言·网络·c++·笔记·网络协议·tcp/ip
Croa-vo1 天前
NVIDIA 2025 Deep Learning & Systems 岗位面试复盘 | C++并发与底层架构难度解析
c++·深度学习·面试