一些C++11语言新特性 - Range-Based for Loops

简介: 1. Range-Based for Loops for ( decl : coll ) { statement}   eg: for ( int i : { 2, 3, 5, 7, 9, 13, 17, 19 } ) { std::cout

1. 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;
}

 

目录
相关文章
|
29天前
|
设计模式 安全 算法
【C++ 基础】超越边界:C++中真正不受访问修饰符限制的特性
【C++ 基础】超越边界:C++中真正不受访问修饰符限制的特性
36 0
|
29天前
|
设计模式 存储 缓存
【C++ 基本概念】深入探索C++ RTTI 特性
【C++ 基本概念】深入探索C++ RTTI 特性
61 0
|
28天前
|
自然语言处理 编译器 C语言
【C++ 20 新特性】参数包初始化捕获的魅力 (“pack init-capture“ in C++20: A Deep Dive)
【C++ 20 新特性】参数包初始化捕获的魅力 (“pack init-capture“ in C++20: A Deep Dive)
38 0
|
29天前
|
Linux C++ iOS开发
【C++ 17 新特性 文件管理】探索C++ Filesystem库:文件和目录操作的全面指南(二)
【C++ 17 新特性 文件管理】探索C++ Filesystem库:文件和目录操作的全面指南
249 2
|
29天前
|
Linux API C++
【C++ 17 新特性 文件管理】探索C++ Filesystem库:文件和目录操作的全面指南(一)
【C++ 17 新特性 文件管理】探索C++ Filesystem库:文件和目录操作的全面指南
310 2
|
6天前
|
缓存 编译器 API
NumPy与其他语言(如C/C++)的接口实践
【4月更文挑战第17天】本文介绍了NumPy与C/C++的接口实践,包括Python与C/C++交互基础、NumPy的C API和Cython的使用。通过案例展示了如何将C++函数与NumPy数组结合,强调了内存管理、类型匹配、错误处理和性能优化的最佳实践。掌握这些技能对于跨语言交互和集成至关重要。
|
16天前
|
程序员 C++
C++语言模板学习应用案例
C++模板实现通用代码,以适应多种数据类型。示例展示了一个计算两数之和的模板函数`add&lt;T&gt;`,可处理整数和浮点数。在`main`函数中,展示了对`add`模板的调用,分别计算整数和浮点数的和,输出结果。
12 2
|
24天前
|
存储 安全 编译器
【C++】类的六大默认成员函数及其特性(万字详解)
【C++】类的六大默认成员函数及其特性(万字详解)
35 3
|
27天前
|
算法 安全 编译器
【C++ 17 新特性 折叠表达式 fold expressions】理解学习 C++ 17 折叠表达式 的用法
【C++ 17 新特性 折叠表达式 fold expressions】理解学习 C++ 17 折叠表达式 的用法
23 1
|
29天前
|
Java API 开发工具
【软件设计师备考 专题 】C、C++、Java、Visual Basic、Visual C++等语言的基础知识和应用(三)
【软件设计师备考 专题 】C、C++、Java、Visual Basic、Visual C++等语言的基础知识和应用
30 0

热门文章

最新文章