一些C++11语言新特性 - Range-Based for Loops
2015-06-29 17:02
543 查看
1. Range-Based for Loops
for ( decl : coll ) {
statement
}
eg:
Here, 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 (which sometimes also might be useful).
This means that to avoid calling the copy constructor and the destructor for each element, you should usually declare the current element to be a constant reference. Thus, a generic function to print all elements of a collection should be implemented as follows:
那段range-based for loops代码等价于如下:
for ( decl : coll ) {
statement
}
eg:
for ( int i : { 2, 3, 5, 7, 9, 13, 17, 19 } ) { std::cout << i << std::endl; }
std::vector<double> vec; ... for ( auto& elem : vec ) { elem *= 3; }
Here, 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 (which sometimes also might be useful).
This means that to avoid calling the copy constructor and the destructor for each element, you should usually declare the current element to be a constant reference. Thus, a generic function to print all elements of a collection should be implemented as follows:
template <typename T> void printElements (const T& coll) { for (const auto& elem : coll) { std::cout << elem << std::endl; } }
那段range-based for loops代码等价于如下:
for (auto _pos=coll.begin(); _pos != coll.end(); ++_pos ) { const auto& elem = *_pos; std::cout << elem << std::endl; }
int array[] = { 1, 2, 3, 4, 5 }; long sum=0; // process sum of all elements for (int x : array) { sum += x; } for (auto elem : { sum, sum*2, sum*4 } ) { // print 15 30 60 std::cout << elem << std::endl; }
相关文章推荐
- C/C++求职宝典21个重点笔记(常考笔试面试点)
- 黑马程序员-OC语言-对象和方法之间的关系(听课笔记)
- 一些C++11语言新特性 - Uniform Initialization
- OC语言学习1
- C语言指针访问数组元素
- C++设计模式之工厂方法模式
- C++ GUI Qt4学习笔记(一)
- c++类的改进
- 黑马程序员——C语言之函数与手动编译执行C程序
- 双向循环链表(c++实现)
- C语言指针
- C++ const面试题和相关的解释
- 汉字字频统计程序(Python版+C语言版)
- C++静态数组和动态数组的区别
- C语言判断某个年份是否是闰年
- C++第六章 习题
- 《thinking in c++》Volume 1知识点总结(二)
- C语言逆序输出某个数字
- C++中传值参数和引用参数和指针怎样区别?
- 《thinking in c++》Volume 1知识点总结(一)