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

原文地址:https://www.cnblogs.com/wainiwann/p/9026174.html