码迷,mamicode.com
首页 > 其他好文 > 详细

Range-Based for Loops

时间:2014-06-15 22:11:18      阅读:295      评论:0      收藏:0      [点我收藏+]

标签:des   style   class   blog   code   http   

for ( decl : coll )
{
  statement
}

where decl is the declaration of each element of the passed collection coll and for which the statements specified are called.

 

1. using the initializer list
for ( int i : { 2, 3, 5, 7, 9, 13, 17, 19 } ) 
{
    std::cout << i << std::endl;
}

2. normal container
std::vector<double> vec;
...
for ( auto& elem : vec ) 
{
    elem *= 3;
}

Declaring elem as a reference is important because otherwise the statements in the body of the for loop act on a local copy of the elements in the vector.
To avoid calling the copy constructor and the destructor for each element, you should usually declare the current element to be a constant reference.

template <typename T>
void printElements (const T& coll)
{
    for (const auto& elem : coll) 
    {
        std::cout << elem << std::endl;
    }
}

//which is equivalent to the following:
{
    for (auto _pos=coll.begin(); _pos != coll.end(); ++_pos ) 
    {
        const auto& elem = *_pos;
        std::cout << elem << std::endl;
    }
}    

Which violate the rules introduced in "the philosophy behind of the design of the STL"

//perfectly correct one
template<T>
printElements(iterator<T> begin, iterator<T> end)
{
    for(;begin < end && begin != end; begin ++)
    {
        const auto& element = *begin;
        std::cout << element << std::endl;
   } 
}

 

 

 

Range-Based for Loops,布布扣,bubuko.com

Range-Based for Loops

标签:des   style   class   blog   code   http   

原文地址:http://www.cnblogs.com/Cmpl/p/3785419.html

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