Range-Based for Loops

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;
   } 
}
原文地址:https://www.cnblogs.com/Cmpl/p/3785419.html