zoukankan      html  css  js  c++  java
  • C++11之for循环的新用法《转》

    相关资料:https://legacy.gitbook.com/book/changkun/cpp1x-tutorial/details

    C++11之for循环的新用法

    C++使用如下方法遍历一个容器:

    #include "stdafx.h"
    #include<iostream>
    #include<vector>
    
    int main()
    {
        std::vector<int> arr;
        arr.push_back(1);
        arr.push_back(2);
    
        for (auto it = arr.begin(); it != arr.end(); it++)
        {
            std::cout << *it << std::endl;
        }
    
        return 0;
    }

    其中auto用到了C++11的类型推导。同时我们也可以使用std::for_each完成同样的功能:

    #include "stdafx.h"
    #include<algorithm>
    #include<iostream>
    #include<vector>
    
    void func(int n)
    {
        std::cout << n << std::endl;
    }
    
    int main()
    {
        std::vector<int> arr;
        arr.push_back(1);
        arr.push_back(2);
    
        std::for_each(arr.begin(), arr.end(), func);
    
        return 0;
    }

    现在C++11的for循环有了一种新的用法:

    #include "stdafx.h"
    #include<iostream>
    #include<vector>
    
    int main()
    {
        std::vector<int> arr;
        arr.push_back(1);
        arr.push_back(2);
    
        for (auto n : arr)
        {
            std::cout << n << std::endl;
        }
    
        return 0;
    }

    上述方式是只读,如果需要修改arr里边的值,可以使用for(auto& n:arr),for循环的这种使用方式的内在实现实际上还是借助迭代器的,所以如果在循环的过程中对arr进行了增加和删除操作,那么程序将对出现意想不到的错误。

      其实这种用法在其他高级语言里早有实现,如php,Java,甚至是对C++进行封装的Qt,foreach也是有的。 

    原文地址:http://www.cnblogs.com/jiayayao/p/6138974.html

  • 相关阅读:
    hibernate各种状态
    Persistence createEntityManagerFactory方法使用
    JS数组学习笔记
    ES6笔记之参数默认值(译)
    JS是按值传递还是按引用传递?
    linux awk命令详解
    Linux Shell笔记之sed
    类似微信红包随机分配js方法
    ionic tabs隐藏完美解决
    mustache 获取json数据内数组对象指定元素的方法
  • 原文地址:https://www.cnblogs.com/wainiwann/p/9026174.html
Copyright © 2011-2022 走看看