您的位置:首页 > 运维架构

Range-Based for Loops

2014-06-13 11:01 281 查看
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;

  }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: