• C++遍历(traversal)总结


    遍历:集合中每个元素一次且仅做一次访问。
    C++中存在很多遍历方式,常见如下几种:

    • 传统C for写法
    • 迭代器for写法
    • STL for_each写法
    • C++11迭代器autofor写法
    • C++11 for loop scope写法
    • C++11 STL for_each与lamdba表达式

    下面实例说明字符串与向量的遍历。

    字符串遍历

    string str("abcdefg");

    1.传统C for写法 

    1. for(size_t i=0;i<str.size();i++){
    2. cout << str[i] << endl;
    3. }

    2.迭代器for写法

    1. for(string::iterator it = str.begin();it != str.end();it++){
    2. cout << *it << endl;
    3. }

     3.STL for_each写法

    1. void print(char c){
    2. cout << c << endl;
    3. }
    4. for_each(str.begin(),str.end(),print);

    4.C++11迭代器写法

    1. for(string::iterator it = begin(str);it != end(str);it++){
    2. cout << *it << endl;
    3. }

    或者

    1. for(auto it = begin(str);it != end(str);it++){
    2. cout << *it << endl;
    3. }

    5. C++ 11 for loop scope写法

    1. for(char c : str){
    2. cout << c << endl;
    3. }

    或者

    1. for(auto c : str){
    2. cout << c << endl;
    3. }

     6.C++ 11 STL for_each与lamdba表达式

    for_each(begin(str),end(str),[](char c){cout << c << endl;});

    向量遍历

    1. vector<int> vec;
    2. vec.push_back(1);
    3. vec.push_back(2);
    4. vec.push_back(3);
    5. vec.push_back(4);
    6. vec.push_back(5);

    1.C写法

    1. for(size_t i=0;i<vec.size();i++){
    2. cout << vec[i] << endl;
    3. }

    2.迭代器写法

    1. for(vector<int>::iterator it = vec.begin();it != vec.end();it++){
    2. cout << *it << endl;
    3. }

    3.STL for_each写法

    1. void print(int n){
    2. cout << n << endl;
    3. }
    4. for_each(vec.begin(),vec.end(),print);

    4.C++11迭代器写法

    1. for(vector<int>::iterator it = begin(vec);it != end(vec);it++){
    2. cout << *it << endl;
    3. }

    或者

    1. for(auto it = begin(vec);it != end(vec);it++){
    2. cout << *it << endl;
    3. }

    5.C++ 11 for新语法写法

    1. for(int n : vec){
    2. cout << n << endl;
    3. }

    或者

    1. for(auto n : vec){
    2. cout << n << endl;
    3. }

    6.C++ 11 STL for_each与lamdba表达式

    for_each(begin(vec),end(vec),[](int n){cout << n << endl;});

  • 相关阅读:
    排序算法-----计数排序
    计算机硬件基础
    Hive Lateral View explode列为空时导致数据异常丢失
    如何报考产品总监认证(UCPD)?
    35、CSS进阶——行盒的垂直对齐以及图片底部白边
    2023 最新 PDF.js 在 Vue3 中的使用(长期更新)
    windows编程基础概念
    FastJson2.0介绍和使用
    【听如子说】-python模块系列-AIS编解码Pyais
    【MindSpore易点通】性能调试经验总结下篇
  • 原文地址:https://blog.csdn.net/mxh3600/article/details/127462692