首页 > 代码库 > Range-Based for Loops
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 listfor ( int i : { 2, 3, 5, 7, 9, 13, 17, 19 } ) { std::cout << i << std::endl;}2. normal containerstd::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 onetemplate<T>printElements(iterator<T> begin, iterator<T> end){ for(;begin < end && begin != end; begin ++) { const auto& element = *begin; std::cout << element << std::endl;
}
}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。