for(autowhatever =begin(a); whatever !=end(a); ++whatever) {autox = *whatever;/* ... */} 对于一般的重载了begin和end方法的对象(比如std::vector), 这两个全局函数会调用它们的这两个方法, 对于C风格数组, std::begin 和 std::end 是模板特化的, 简单来说就是特判了【特化为数组的引用】, ...
所有的STL标准容器都适用于该“范围”,例如vector、string等等。数组也同样可以,只要定义了begin()和end()方法的任何“范围”都可以使用for来循环迭代容器里面的元素,如istream。 语法: for(range_declaration:range_expression)loop_statement 上述代码的效果类似于: (__range,__beginand__endare for exposition onl...
6. class IntVector; 7. 8. class Iter 9. { 10. public: 11. const IntVector* p_vec, int pos) 12. : _pos( pos ) 13. , _p_vec( p_vec ) 14. { } 15. 16. // these three methods form the basis of an iterator for use with 17. // a range-based for loop 18. bool 19...
range-based for loop 是 C++11 引入的一种新的循环结构,用于遍历容器(如数组、vector、list、set、map 等)中的元素。它的语法非常简洁,使得遍历容器变得更加直观和易读。 基本语法如下: cpp for (declaration : container) { // 循环体 } 示例代码: cpp #include <iostream> #include <vector&...
#include <iostream> #include <vector> int main() { std::vector<int> v = {0, 1, 2, 3, 4, 5}; for (const int& i : v) // access by const reference std::cout << i << ' '; std::cout << '\n'; for (auto i : v) // access by value, the type of i is int std...
__cpp_range_based_for200907L(C++11)Range-basedforloop 201603L(C++17)Range-basedforloop withdifferentbegin/endtypes 202211L(C++23)Lifetime extension for all temporary objects inrange-initializer Keywords for Example Run this code #include <iostream>#include <vector>intmain(){std::vector<int>...
1. Range-Based for Loops for ( decl : coll ) { statement } eg: for(inti : {2,3,5,7,9,13,17,19} ) { std::cout<< i <<std::endl; } 1. 2. 3. std::vector<double>vec; ...for( auto&elem : vec ) { elem*=3; ...
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: " <...
C++11支持range-based for循环。这是一个很方便的特性,能省挺多代码。以下代码就能很方便的遍历vector中的元素,并打印出来: std::vector<int> int_vec; int_vec.push_back(1); int_vec.push_back(2); //如果要修改int_vec中的元素,将变量x声明为 int& 即可 ...
The last rule (the fallback to the free-standingbegin()andend()functions) allows us to non-invasively adapt an existing container to the range-basedforloop interface. 0.2 类型推断 std::vector<int> v = {1, 2, 3, 5, 7, 11};