Range-Based For Loop
Part of the Logic & Flow section of Coddy's C++ journey — lesson 15 of 56.
While traditional for loops with indices work well for iterating through vectors, C++ offers a more elegant solution: the range-based for loop. This modern syntax eliminates the need for manual index management and makes your code cleaner and easier to read.
The range-based for loop automatically handles the iteration details for you. Instead of managing an index variable, you simply specify what you want to do with each element:
std::vector<std::string> names = {"Alice", "Bob", "Charlie"};
for (const std::string& name : names) {
std::cout << name << std::endl;
}This loop does exactly the same thing as the traditional index-based approach, but with much simpler syntax. The name variable automatically takes on the value of each element in the vector, one at a time.
Notice the
& in const std::string& name. Here, & does not mean "address of" as you may have seen before — in a variable declaration like this, it means reference (or alias). Instead of copying each element, name becomes an alias that refers directly to the element in the vector, similar to using a pointer but without needing to dereference it inside the loop body.The
const keyword is a safety measure: it prevents you from accidentally modifying the element through the alias inside the loop body, keeping the original vector data unchanged.The range-based for loop is not only more readable but also safer - there's no risk of index errors since you're not managing indices manually. It works with any container that supports iteration, making it a versatile tool for processing collections of data in C++.
Challenge
EasyCreate a program that demonstrates the range-based for loop by processing a collection of city names and displaying them with their character counts.
The following inputs will be provided:
- An integer
nrepresenting the number of cities - Then
nstrings representing city names
Your program should:
- Create a
std::vector<std::string>namedcities - Use
push_back()to add each of thencity names to the vector - Use a range-based for loop to iterate through the vector
- For each city in the loop, print the city name followed by its length using the
.length()method - After the loop, print the total number of cities processed using the vector's
.size()method
Use the following exact output format:
City: [city name] (Length: [number of characters])\nCity: [city name] (Length: [number of characters])\n...\nTotal cities processed: [total count]The range-based for loop should use the syntax for (const std::string& city : cities) to iterate through each element in the vector. Use city.length() to get the number of characters in each city name.
Cheat sheet
The range-based for loop iterates through a container without manual index management:
std::vector<std::string> names = {"Alice", "Bob", "Charlie"};
for (const std::string& name : names) {
std::cout << name << std::endl;
}&declaresnameas a reference (alias) to each element — no copyingconstprevents accidental modification of the element inside the loop body- Works with any container that supports iteration
Try it yourself
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
// Read the number of cities
int n;
cin >> n;
// Create a vector to store city names
vector<string> cities;
// Read city names and add them to the vector
for (int i = 0; i < n; i++) {
string city;
cin >> city;
cities.push_back(city);
}
// TODO: Write your code below
// Use a range-based for loop to iterate through the cities vector
// Print each city with its length using the specified format
// After the loop, print the total number of cities processed
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Pointers and Memory
What is a Pointer?Address-Of OperatorDereference OperatorNull PointersPointers and ArraysDynamic Memory with 'new'Freeing Memory with 'delete'Recap - Pointer Practice2Vectors (Dynamic Arrays)
Introducing std::vectorCreating a VectorAdding ElementsAccessing ElementsVector SizeIterating with a For LoopRange-Based For LoopRemoving ElementsRecap - Vector Operations5Project: Inventory Tool
Project SetupAdding and Updating Items