Iterate over a Set in C++

In this article, we will discuss different ways to iterate or loop over a Set in C++.

Introduction

Suppose we have a Set of strings. Like this,

// Set of Strings
std::set<std::string> setOfStr = { "the",
                                    "is",
                                    "of",
                                    "from",
                                    "at",
                                    "hello",
                                    "the" };

Now, we want to iterate over all the elements in set and print them on screen. We ca do that using different methods, let’s discuss them one by one.

Iterate over a Set using Iterators

The set::begin() function returns an iterator pointing to the first element in set. Whereas, set::end() function returns an iterator past the end of set.

Now to iterate a set in forward direction, we need to create an iterator and initialise it with set::begin(). So that it points to start of set and then we will keep on accessing elements using iterator and increment the iterator to next till set::end() is reached. Like this,

// Creating a iterator pointing to start of set
std::set<std::string>::iterator it = setOfStr.begin();

// Iterate over set elements till the end of set
while (it != setOfStr.end())
{
    // Print the element
    std::cout << (*it) << ", ";

    //Increment the iterator
    it++;
}

Here, we iterated the set in forward direction. Now, let’s see how to iterate in reverse direction.

Output



    at, from, hello, is, of, the,

    Iterate over a Set in backward direction

    The set::rbegin() returns a reverse_iterator pointing to the last element of set. Whereas, set::rend() returns a reverse_iterator pointing to element before the first element.

    Now to iterate a set in reverse direction, we need to create an reverse_iterator and initialise it with set::rbegin(). So that it points to the last element of set and then we will keep on access and increment the iterator to next till set::rend() is reached i.e. beginning of set.

    // Creating a reverse iterator pointing to end of set i.e. rbegin
    std::set<std::string>::reverse_iterator revIt = setOfStr.rbegin();
    
    // Iterate till the start of set i.e. rend
    while (revIt != setOfStr.rend())
    {
        // Print the element
        std::cout << (*revIt) << ", ";
    
        //Increment the iterator
        revIt++;
    }
    std::cout<< std::endl;

    Output

    the, of, is, hello, from, at, 

    Iterating over a Set using Range base for loop

    C++11 introduced the range based for loop in C++. Using that we can iterate over any container in C++, without using iterator. We just need to provide a variable in for loop statement, and that will be initialized with each element in container. Like here, we are going to iterate over all elements of Set using range based foe loop.

    // Iterate over all elements of set
    // using range based for loop
    for (auto elem : setOfStr)
    {
        std::cout << elem << " , ";
    }
    std::cout<< std::endl;

    Output

    at , from , hello , is , of , the , 

    Iterating over a Set using std::for_each() & Lambda Function

    We can pass a Lambda Function and start, end iterator to for_each() function. It will apply the given lambda function on each element of Set. Inside the lambda function we can print the contents of element. This we can loop over all the elements of Set. For example,

    // Iterate over all elements using for_each
    // and lambda function
    std::for_each(
            setOfStr.begin(),
            setOfStr.end(),
            [](const std::string & str) {
                        std::cout<<str<<" , ";
            });

    Output

    at , from , hello , is , of , the , 

    The complete example is as follows,

    #include <iostream>
    #include <algorithm>
    #include <string>
    #include <set>
    
    
    int main()
    {
        // Set of Strings
        std::set<std::string> setOfStr = { "the",
                                            "is",
                                            "of",
                                            "from",
                                            "at",
                                            "hello",
                                            "the" };
    
        // Creating a iterator pointing to start of set
        std::set<std::string>::iterator it = setOfStr.begin();
    
        // Iterate over set elements till the end of set
        while (it != setOfStr.end())
        {
            // Print the element
            std::cout << (*it) << ", ";
    
            //Increment the iterator
            it++;
        }
        std::cout<< std::endl;
    
    
        // Creating a reverse iterator pointing to end of set i.e. rbegin
        std::set<std::string>::reverse_iterator revIt = setOfStr.rbegin();
    
        // Iterate till the start of set i.e. rend
        while (revIt != setOfStr.rend())
        {
            // Print the element
            std::cout << (*revIt) << ", ";
    
            //Increment the iterator
            revIt++;
        }
        std::cout<< std::endl;
    
    
        // Iterate over all elements of set
        // using range based for loop
        for (auto elem : setOfStr)
        {
            std::cout << elem << " , ";
        }
        std::cout<< std::endl;
    
    
        // Iterate over all elements using for_each
        // and lambda function
        std::for_each(
                setOfStr.begin(),
                setOfStr.end(),
                [](const std::string & str) {
                            std::cout<<str<<" , ";
                });
    
        std::cout<< std::endl;
    
        return 0;
    }

    Output:

    at, from, hello, is, of, the, 
    the, of, is, hello, from, at, 
    at , from , hello , is , of , the , 
    at , from , hello , is , of , the , 

    Summary

    We learned about different ways to iterate over a Set in C++.

    Scroll to Top