zoukankan      html  css  js  c++  java
  • 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也是有的。 

  • 相关阅读:
    字符串转换整数 (atoi)
    Z 字形变换
    最长回文子串
    寻找两个有序数组的中位数
    二维码QRCode
    多个线程访问url
    store procedure 翻页
    store procedure example
    使用graphics2D给图片上画字符
    procedure的over(partition by ) function
  • 原文地址:https://www.cnblogs.com/jiayayao/p/6138974.html
Copyright © 2011-2022 走看看