C++11 Range-based for Loop

beginner
14 min

C++11 Range-based for Loop

Welcome to our deep dive into the C++11 Range-based for Loop! In this lesson, we'll explore this powerful tool that simplifies iterating over collections in C++. Let's get started!

What is a Range-based for Loop?

The range-based for loop is an innovative feature introduced in C++11 that allows you to iterate over a range of elements directly, without the need for explicit iteration variables.

šŸ’” Pro Tip: This loop is especially useful when you want to perform the same operation on all elements in a collection, making your code cleaner and more efficient!

Syntax

The range-based for loop has a simple syntax:

cpp
for (range_declaration : range) { // code to be executed for each element }
  • range_declaration: This is where we declare an iterator type for our collection.
  • range: This is the collection we want to iterate over, such as a vector, array, or list.

Example 1: Iterating over a Vector

Let's take a look at a practical example:

cpp
#include <iostream> #include <vector> int main() { std::vector<int> numbers = {1, 2, 3, 4, 5}; for (int number : numbers) { std::cout << number << std::endl; } return 0; }

In this example, we have a vector of integers named numbers. We declare an int variable number as our iterator type and iterate over the numbers vector. For each element, we print its value to the console.

šŸ“ Note: In C++, when we don't specify a type for an iterator, the compiler automatically deduces the type for us.

Example 2: Iterating over a String

Now let's explore a real-world example, where we'll iterate over a string:

cpp
#include <iostream> #include <string> int main() { std::string name = "John Doe"; for (char c : name) { std::cout << c; } std::cout << std::endl; return 0; }

In this example, we have a string name. We declare a char variable c as our iterator type and iterate over the name string. For each character, we print it to the console.

Quiz

Quick Quiz
Question 1 of 1

What does the C++11 range-based for loop allow us to do?

Stay tuned for more in-depth exploration of the C++11 Range-based for Loop, including advanced examples and best practices! šŸš€