zoukankan      html  css  js  c++  java
  • 论C++11 中vector的N种遍历方法

    转载:https://www.cnblogs.com/xylc/p/3653036.html

    随着C++11标准的出现,C++标准添加了许多有用的特性,C++代码的写法也有比较多的变化。

    vector是经常要使用到的std组件,对于vector的遍历,本文罗列了若干种写法。

    (注:本文中代码为C++11标准的代码,需要在较新的编译器中编译运行)

    假设有这样的一个vector:(注意,这种列表初始化的方法是c++11中新增语法)

    vector<int> valList = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    需要输出这个vector中的每个元素,测试原型如下:

    复制代码
    void ShowVec(const vector<int>& valList)
    {
    }
    int main(int argc, char* argv[])
    {
        vector<int> valList = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        ShowVec(valList);
        return 0;
    }
    复制代码

    下面就开始我们的茴香豆的N种写法吧 !

    方法零,对C念念不舍的童鞋们习惯的写法:

    复制代码
    void ShowVec(const vector<int>& valList)
    {
        int count = valList.size();
        for (int i = 0; i < count;i++)
        {
            cout << valList[i] << endl;
        }
    }
    复制代码

     或者

    1
    2
    3
    4
    5
    6
    7
    8
    void ShowVec(const vector<int>& valList)
    {
        int count = valList.size();
        for (int i = 0; i < count;i++)
        {
            cout << valList.at(i) << endl;
        }
    }

    方法一,大家喜闻乐见的for循环迭代器输出,(注意,此处使用了C++11中新增的标准库容器的cbegin函数)

    复制代码
    void ShowVec(const vector<int>& valList)
    {
        for (vector<int>::const_iterator iter = valList.cbegin(); iter != valList.cend(); iter++)
        {
            cout << (*iter) << endl;
        }
    }
    复制代码

    或者使用c++新增的语义auto,与上面差不多,不过能少打几个字:

    复制代码
    void ShowVec(const vector<int>& valList)
    {
        for (auto iter = valList.cbegin(); iter != valList.cend(); iter++)
        {
            cout << (*iter) << endl;
        }
    }
    复制代码

    方法二,for_each加函数:

    复制代码
    template<typename T>
    void printer(const T& val)
    {
        cout << val << endl;
    }
    void ShowVec(const vector<int>& valList)
    {
        for_each(valList.cbegin(), valList.cend(), printer<int>);
    }
    复制代码

    方法三,for_each加仿函数:

    复制代码
    template<typename T>
    struct functor
    {
        void operator()(const T& obj)
        {
            cout << obj << endl;
        }
    };
    void ShowVec(const vector<int>& valList)
    {
        for_each(valList.cbegin(), valList.cend(), functor<int>());
    }
    复制代码

    方法四,for_each加Lambda函数:(注意:lambda为c++11中新增的语义,实则是一个匿名函数)

    void ShowVec(const vector<int>& valList)
    {
        for_each(valList.cbegin(), valList.cend(), [](const int& val)->void{cout << val << endl; });
    }

    方法五,for区间遍历:(注意,for区间遍历是c++11新增的语法,用于迭代遍历数据列表)

    for (auto val : valList)
    {
        cout << val << endl;
    }
  • 相关阅读:
    并行和并发
    怎样用第三方开源免费软件portecle从https站点上导出SSL的CA证书?
    我持续推动Rust语言支持Windows XP系统
    Android——4.2.2 文件系统文件夹分析
    hadoop(八)
    自己定义html中a标签的title提示tooltip
    多个返回 顶部的代码
    同学们,OpenCV出3.0了,速去围观!
    hdu1002
    好记性不如烂笔头(一)
  • 原文地址:https://www.cnblogs.com/shiheyuanfang/p/13898165.html
Copyright © 2011-2022 走看看