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;
} }
相关文章推荐
- C++11新特性之四:range-based for loops
- 一些C++11语言新特性 - Range-Based for Loops
- C++ 11 学习2:空指针(nullptr) 和 基于范围的for循环(Range-based for loops)
- C++11中range-based for loops中&&与&的区别
- 自定义类型使用range-based for loops
- C++11 性能Range-based for loops
- C++11 range-based for loops
- C++ 11 学习2:空指针(nullptr) 和 基于范围的for循环(Range-based for loops)
- C++11 新特性之Range-based for loops
- How to change mode from c++98 mode in Dev-C++ to a mode that supports C++0x (range based for)?
- C++11中的有趣的新特性(constexpr ) (Range-based for loop)
- Code::Blocks error: range-based 'for' loops are not allowed in C++98 mode
- 自定义数据结构的基于范围的for循环 range-based for loop
- C++11新特性之基本范围的For循环(range-based-for)
- c++11 : range-based for loop
- Modern C++(二)Range-based for loop(基于范围的for循环)
- C++11新特性:range based for loop-范围for循环基本使用方法
- c++11 : range-based for loop
- C++11 | range-based for loop
- Search for a Range