From the course: C++ Best Practices for Developers

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Range-based for loops

Range-based for loops - C++ Tutorial

From the course: C++ Best Practices for Developers

Start my 1-month free trial

Range-based for loops

- [Instructor] C plus plus can iterate over a range of values automatically. No need for indexing. It can iterate over STL containers, strings, and arrays. You can add support for range-based for loops to your own types by supporting the iterator interface. Prefer range-based for loops over traditional for loops, but always ask yourself twice before implementing any raw loop if you can replace it with an algorithm from the STL. Let's see some code examples. So in our first example, we're just iterating over a vector of int, and you notice the format is just four, and then we got auto I colon, and then the vector of int which is v. Then we have it iterating over a initialized list, and so we don't even have to declare it as a variable. We can just put the raw list right inside the for loop, and then we have it iterating over just standard arrays. It can even iterate over strings, and we can iterate over map. So let's just take a quick look at it in code. Let's go ahead and compile…

Contents