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
相关推荐
乔宕一2 小时前
stm32 链接脚本没有 .gcc_except_table 段也能支持 C++ 异常
c++·stm32·嵌入式硬件
SuperCandyXu2 小时前
P3205 [HNOI2010] 合唱队-普及+/提高
c++·算法·洛谷
_君落羽_2 小时前
ARM寄存器以及异常处理
c++
free2 小时前
基于librdkafa C++客户端生产者发送数据失败问题处理#2
c++·kafka
小柯J桑_3 小时前
Linux:线程封装
linux·运维·c++
doll ~CJ4 小时前
基于QVTKOpenGLNativeWidget的三维点云可视化实现
c++·qt·软件开发·三维点云可视化
42fourtytoo5 小时前
天津大学智算2026预推免机试第二批题目及代码c++
开发语言·c++·面试
子豪-中国机器人5 小时前
枚举算法和排序算法能力测试
开发语言·c++·算法
1白天的黑夜15 小时前
栈-844.比较含退格的字符串-力扣(LeetCode)
c++·leetcode·
林夕忆梦_猫6 小时前
初识C++
开发语言·c++