码迷,mamicode.com
首页 > 编程语言 > 详细

c++ 11 基于范围的for循环

时间:2015-08-02 21:40:47      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

基于范围的for循环:
对于内置数组以及包含方法begin()和end()的类(如std::string)和STL容器,基于范围的for循环可以简化为他们编写循环的工作。这种循环对数组或容器中的每个元素执行指定的操作:

#include <iostream>
int main()
{
    double prices[5] = {4.99,10.99,6.87,7.99,8.49};
    for (double x : prices)
       std::cout << x << std::endl;
    return 0;
}

技术分享

其中,x将依次为prices中每个元素的值。x的类型应与数组元素的类型匹配。 一种更容易更安全的方式是,使用auto来声明x,这样编译器将根据prices声明的信息来推断x的类型:

for (auto x : prices)
    std::cout << x << std::endl;

如果要在循环中修改数组或容器的每个元素,可使用引用类型:

std::vector<int> vi(6);
for (auto &x : vi)
    x = std::rand();

版权声明:本文为博主原创文章,未经博主允许不得转载。

c++ 11 基于范围的for循环

标签:

原文地址:http://blog.csdn.net/nizhannizhan/article/details/47210549

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!