首页 > 其他 > 详细

Range-Based for Loops

时间:2014-06-15 22:10:25      阅读:299      评论:0      收藏:0      [点我收藏+]
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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!