How to Use Range Based For Loops with Set in C++11 and later?

This tutorial will discuss how to use range based for loops with set in C++11 and later.

In C++11, the range-based for loop was introduced. It allows us to iterate over a sequence of elements without explicitly using an iterator or random-access operators.

In the range-based for loop, we only need to specify a variable that will temporarily hold the value from the sequence and the container, separated by a colon. For instance, in the following pseudo-code:

for (auto value : container)
{
    // use value inside the loop
}

We can iterate over all the elements of the set. During each iteration, the current element will be assigned to the value variable, and within the loop block, we can directly access that value.

std::set<int> numbers = {23, 45, 44, 21, 22, 60};

// Range-based for loop to iterate over a set
for (const auto& value : numbers)
{
    std::cout << value << " ";
}

Output:

21 22 23 44 45 60

No iterators are required with the range-based for loop.

Let’s see the complete example,

#include <iostream>
#include <set>

int main()
{
    std::set<int> numbers = {23, 45, 44, 21, 22, 60};

    // Range-based for loop to iterate over a set
    for (const auto& value : numbers)
    {
        std::cout << value << " ";
    }
    std::cout<< std::endl;

    return 0;
}

Output

21 22 23 44 45 60

Summary

Today, we learned how to use range based for loops with set in C++11 and later.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top