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
相关推荐
派阿喵搞电子1 小时前
在UI界面内修改了对象名,在#include “ui_mainwindow.h“没更新
c++·qt·ubuntu·ui
C++ 老炮儿的技术栈2 小时前
UDP 与 TCP 的区别是什么?
开发语言·c++·windows·算法·visual studio
mochensage4 小时前
CSP信奥赛C++常用系统函数汇总
c++·信奥
mochensage4 小时前
C++信息学竞赛中常用函数的一般用法
java·c++·算法
fpcc4 小时前
跟我学c++中级篇——多线程中的文件处理
c++
5:005 小时前
云备份项目
linux·开发语言·c++
乄夜6 小时前
嵌入式面试高频(5)!!!C++语言(嵌入式八股文,嵌入式面经)
c语言·c++·单片机·嵌入式硬件·物联网·面试·职场和发展
YYDS3146 小时前
C++动态规划-01背包
开发语言·c++·动态规划
wydaicls6 小时前
十一.C++ 类 -- 面向对象思想
开发语言·c++
姜君竹7 小时前
QT的工程文件.pro文件
开发语言·c++·qt·系统架构