VOOZH about

URL: https://www.geeksforgeeks.org/cpp/range-based-for-loop-with-map-in-cpp/

⇱ Range-Based For Loop with a Map in C++ - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Range-Based For Loop with a Map in C++

Last Updated : 23 Jul, 2025

In C++, a map is a container that stores elements formed by a combination of a key value and a mapped value. A range-based for loop is a feature added in C++11 to iterate over containers. In this article, we will learn how to use a range-based for loop with a map in C++.

Example:

Input:
myMap: { {1, “John”}, {2, “Adam”} }
Output:
1: John
2: Adam

Range-Based for Loop with a Map in C++

We can use the range-based for loop with a std::map to replace any other loop and simplify the code. The range-based for loop will take the name of the map and iterator over each element in the container.

C++ Program to Traverse Map with Range Based for Loop


Output
Ranged-based for loop with read-only iterator
Apple: 50
Banana: 25
Mango: 30
Orange: 20
Ranged-based for loop with writable iterator
Apple: 60
Banana: 35
Mango: 40
Orange: 30

Time Complextiy: O(N logN), where N is the number of elements.
Space Complexity: O(1)



Comment
Article Tags: