Search⌘ K
AI Features

Range-based for Loop with Initializers

Explore the enhancements in C++20 that allow using range-based for loops with initializers. Understand how to apply this feature with various container types like std::vector, std::initializer_list, and std::string using automatic type deduction for cleaner code.

We'll cover the following...

With C++20, you can directly use a range-based for loop with an initializer.

C++
#include <iostream>
#include <string>
#include <vector>
int main() {
for (auto vec = std::vector{1, 2, 3}; auto v : vec) {
std::cout <<v <<" ";
}
std::cout << "\n\n";
for (auto initList = {1, 2, 3}; auto e : initList) {
e *= e;
std::cout << e << " ";
}
std::cout << "\n\n";
using namespace std::string_literals;
for (auto str = "Hello World"s; auto c: str) {
std::cout << c << " ";
}
std::cout << '\n';
}

The range-based for ...