From the course: Complete Guide to C++ Programming Foundations
Unlock this course with a free trial
Join today to access over 24,800 courses taught by industry experts.
Ranged for loops - C++ Tutorial
From the course: Complete Guide to C++ Programming Foundations
Ranged for loops
- [Instructor] Let me show you another form of the for loop that was introduced in the C++11 standard. This is the range-based for loop, and as the name suggests, it works by traversing a specified range with an iterator. Here we have the same code we used for the traditional for loop, and I will simply modify lines 13 and 14 to use a ranged for loop. The syntax is quite simple. First, you specify a variable to traverse the container, then a colon, and then the name of the container. In our case, let me declare an integer, but I'll use the autotype and name it x. Then comes a colon and the name of the vector. You may read this as for each x in lapTimes, do the following. Now, be warned that using a variable of the same type as the elements in a vector or array will copy the value of each element into the variable for each iteration of the loop. So this is okay in this example where we have a vector of integers. However, if you have a vector of large objects, you may want to use a…