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
相关推荐
NiceCloud喜云8 小时前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
cjhbachelor8 小时前
c++继承
c++
肩上风骋9 小时前
C++14特性
开发语言·c++·c++14特性
QiLinkOS12 小时前
【从实验室到商业战场:发明专利如何重塑科技与企业的共生生态】
大数据·c语言·数据结构·c++·人工智能·单片机·算法
Irissgwe12 小时前
c++11(lambda表达式与包装器、线程库)
c++·c++11·lambda表达式·线程库·包装器·互斥量库·条件变量库
Peter·Pan爱编程13 小时前
14. Lambda 表达式:随手可写的函数对象
c++·算法·ai编程
不想写代码的星星14 小时前
从分支预测角度看 C++:为什么你的热循环慢得离谱?
c++
郝学胜-神的一滴14 小时前
Qt 高级开发 018:复刻经典登录界面布局与窗口美化全解析
开发语言·c++·qt·程序人生·用户界面
郝亚军14 小时前
IEEE 754 单精度浮点的SEM表示
开发语言·c++·算法
Yyyyyy~16 小时前
【C++】数组篇
开发语言·c++