• 【C++】常用遍历算法


    目录

    for_each

    transform


    常用算法概述

    • 算法主要有头文件
    •  是所有 STL 头文件中最大的一个,涉及 比较交换查找遍历操作修改
    •  定义了一些模板类,用来声明内建函数对象(仿函数)
    • 体积小,只包含几个在序列上面进行简单数学运算的模板函数

    for_each

    功能

    • 实现遍历容器,遍历容器元素

    函数原型

    for_each(iterator beg, iterator end, _func);

    beg   —— 开始迭代器

    end   —— 结束迭代器

    _func—— 函数或者函数对象

    测试代码:

    1. #include
    2. using namespace std;
    3. #include
    4. #include
    5. #include
    6. class Person {
    7. public:
    8. Person(string name, int age) :m_Name(name), m_Age(age) {}
    9. string m_Name;
    10. int m_Age;
    11. };
    12. // 普通函数
    13. void PrintVector1(Person& p) {
    14. cout << p.m_Name << " " << p.m_Age << endl;
    15. }
    16. // 仿函数
    17. class PrintVector2 {
    18. public:
    19. void operator()(Person& p) {
    20. cout << p.m_Name << " " << p.m_Age << endl;
    21. }
    22. };
    23. void test() {
    24. vectorPV;
    25. Person p1("张三", 19);
    26. Person p2("李四", 20);
    27. Person p3("王五", 18);
    28. PV.push_back(p1);
    29. PV.push_back(p2);
    30. PV.push_back(p3);
    31. // 普通函数
    32. for_each(PV.begin(), PV.end(), PrintVector1);
    33. // 函数对象
    34. for_each(PV.begin(), PV.end(), PrintVector2());
    35. }
    36. int main() {
    37. test();
    38. system("pause");
    39. return 0;
    40. }

    运行结果:


    transform

    功能

    • 搬运容器到另一个容器

    函数原型

    transform(iterator beg1, iterator end1, iterator beg2, _func);

    beg1  —— 源容器开始迭代器

    end1  —— 源容器结束迭代器

    beg2  —— 目标容器开始迭代器

    _func —— 函数或者函数对象

    测试代码:

    1. #include
    2. using namespace std;
    3. #include
    4. #include
    5. class Transform {
    6. public:
    7. int operator()(const int& val) {
    8. return val;
    9. }
    10. };
    11. class Print {
    12. public:
    13. void operator()(const int& val) {
    14. cout << val << " ";
    15. }
    16. };
    17. void test() {
    18. vector<int>v1;
    19. for (int i = 0; i < 10; ++i) {
    20. v1.push_back(i);
    21. }
    22. vector<int>v2; // 目标容器
    23. // 目标容器提前开辟空间
    24. v2.resize(v1.size());
    25. transform(v1.begin(), v1.end(), v2.begin(), Transform());
    26. for_each(v2.begin(), v2.end(), Print());
    27. }
    28. int main() {
    29. test();
    30. system("pause");
    31. return 0;
    32. }

    运行结果:

  • 相关阅读:
    在Linux系统上用nmap扫描SSL漏洞的方法
    Codeforces Round 901 (Div. 2) | JorbanS
    mybatis嵌套查询子集合只有一条数据
    vue-h5移动Web的Flex布局
    菜小白聊聊开源和开源协议
    完全解析Array.apply(null, { length: 1000 })
    Servlet规范之过滤器Filter
    算法:只使用一个int类型变量表示日期
    echarts 类目轴设置xAxis.interval不起效果
    【蓝桥杯省赛真题14】python围圈报数 青少年组蓝桥杯python编程省赛真题解析
  • 原文地址:https://blog.csdn.net/xuan3215/article/details/126171121