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
相关推荐
观鉴词recommend15 分钟前
【c++刷题笔记-动态规划】day32: 509. 斐波那契数 、 70. 爬楼梯 、 746. 使用最小花费爬楼梯
c++·笔记·算法·leetcode·动态规划
DieSnowK16 分钟前
[C++][ProtoBuf][初识ProtoBuf]详细讲解
开发语言·c++·google·协议·序列化·反序列化·protobuf
酷酷学!!!28 分钟前
C++第一弹 -- C++基础语法上(命名空间 输入输出 缺省参数 函数重载 引用)
开发语言·c++·学习方法·visual studio
郝YH是人间理想29 分钟前
《算法笔记》总结No.3——排序
c语言·数据结构·c++·算法·排序算法·csp
semicolon_hello1 小时前
使用C++编写TCP服务端程序
服务器·网络·c++·tcp/ip
L小李要学习1 小时前
十一、作业
c语言·开发语言·c++
听听听搁浅1 小时前
数论知识(取模运算)
c++·数论
Ddddddd_1582 小时前
C++ | Leetcode C++题解之第216题组合总和III
c++·leetcode·题解
每天努力进步!2 小时前
LeetCode热题100刷题8:54. 螺旋矩阵、73. 矩阵置零、48. 旋转图像
c++·算法·leetcode·矩阵
观鉴词recommend2 小时前
【c++刷题笔记-贪心】day28: 134. 加油站 、 135. 分发糖果 、860.柠檬水找零 、 406.根据身高重建队列
c++·笔记·算法·leetcode