基于范围的for 循环(Range-based for loop)是 C++11 标准引入的一项特性,它提供了一种更简洁、更安全的遍历容器(如数组、向量等)的方式。 与传统的 for 循环相比,基于范围的 for 循环自动处理迭代,避免了迭代器或下标可能引入的错误,使代码更加易于编写和理解。 基本语法 基于范围的 for 循环的基本语法如下: fo...
所以for循环可以正常执行。 但是在修改过后,range_expression是 "MyClass().getText()"。同样地,MyClass()是临时对象,"MyClass()" 这个表达式是右值。但是 "getText()" 的返回类型为 "string&",所以,"MyClass().getText()" 这个表达式是左值。所以,在 "auto && __range = range_expression;" 这个语句中,...
所以for循环可以正常执行。 但是在修改过后,range_expression是 "MyClass().getText()"。同样地,MyClass()是临时对象,"MyClass()" 这个表达式是右值。但是 "getText()" 的返回类型为 "string&",所以,"MyClass().getText()" 这个表达式是左值。所以,在 "auto && __range = range_expression;" 这个语句中,...
7. loop_statement 8. } 9. } 1. 2. 3. 4. 5. 6. 7. 8. 9. 请注意,“等价于”并不表示编译器就是这么实现range-based for loops的。只是说两者的运行效果等价 begin_expr 和 end_expr 的定义如下: 对于数组类型 begin_expr和end_expr分别等于(__range)和(__range + __bound) 对于STL中的容...
; for (auto &c : s) { /* ... */ } 直觉上c的类型应该是const char&,但是怎么推理得到c的类型呢?细究起来确实花了一番功夫。 使用auto声明的变量必须要给初始值,而这里的语法没有给初始值。Range-Based for loop应该是一种语法糖,实际上编译器应该是当成普通的for循环来处理的。 从cppreference(...
直觉上`c`的类型应该是`const char&`,但是怎么推理得到`c`的类型呢?细究起来确实花了一番功夫。 使用auto声明的变量必须要给初始值,而这里的语法没有给初始值。Range-Based for loop应该是一种语法糖,实际上编译器应该是当成普通的for循环来处理的。
When used with a (non-const) object that has copy-on-write semantics, the range-basedforloop may trigger a deep copy by (implicitly) calling the non-constbegin()member function. If that is undesirable (for instance because the loop is not actually modifying the object), it can be avoided...
Range-based for loop Range-based for loop 在范围上执行for循环。 用作更易读的,相当于传统的用于循环操作范围内的值,例如容器中的所有元素。 句法 attr(optional) for ( range_declaration : range_expression ) loop_statement attr - any number of attributes range_declaration - a declaration ...
// Range-based for loop to iterate through the array. for( int y : x ) // Access by value using a copy declared as a specific type. // Not preferred. cout << y << " "; cout << endl; // The auto keyword causes type inference to be used. Preferred. ...
The range-based for loop follows this general format:for( declaration : expression) { //do some loop stuff } C++ CopyHere’s an simple example which prints all the elements in a std::vector:std::vector<int> v1 = {-1, 3, 5, -8, 0}; std::cout << std::endl << "v1: " <...