A Set is an important Container provided by Standard Template Library in C++. It stores unique elements only and that too in a sorted order. Iterating over a set is a fundamental operation, and in this article, we’ll learn different ways to loop over a set and access its elements

Access Set Elements Using Iterators

A set provides support for iterators to access and traverse the elements. Suppose if we call the begin() function on the set object, it will return an iterator pointing to the first element of the set. We can access the value using the iterator by dereferencing it.

std::set<int> setObj = {11, 33, 44, 77};

// Using iterator to access elements
std::set<int>::iterator it = setObj.begin();

// Outputs the first element: 11
std::cout << *it << " "; 

We can also increment the iterator to move it to the next element. If we add 1 to the iterator, it will point to the next, essentially the second element, of the set.

// Move to the next element
++it;                    

// Outputs: 33
std::cout << *it << " "; 

We can use this logic to iterate over all the elements of the set. Let’s see an example where we will create a set of integers. We will then call the begin function to get an iterator pointing to the first element of the set. We will print the value using that iterator. After that, we will increment the iterator to make it point to the next element and print that value too. We will do this again to print the third value.

Let’s see this complete example,

#include <iostream>
#include <set>

int main()
{
    std::set<int> setObj = {11, 33, 44, 77};

    // Using iterator to access elements
    std::set<int>::iterator it = setObj.begin();

    // Outputs the first element: 11
    std::cout << *it << " "; 

    // Move to the next element
    ++it;                    
    // Outputs: 33
    std::cout << *it << " "; 

    // Move to the next element
    ++it;                    
    // Outputs: 44
    std::cout << *it << " "; 

    return 0;
}

Output:

11 33 44

Here, we’ve initialized an iterator it with the first element of the set using begin(). We then move to subsequent elements by incrementing the iterator.

Loop Set Elements Using Iterators

Using an iterator, we can iterate over all the elements of the set. For this, we will initialize our iterator with the value returned by the begin function of the set. Then, we will keep on incrementing the iterator in a for loop until it reaches the end of the set, basically when the iterator is equal to the value returned by the end function of the set.

Let’s see an example where we will initialize a set of integers with default values. Then, we will use iterators to iterate over all the integers in the set and print them one by one on the console.

#include <iostream>
#include <set>

int main()
{
    std::set<int> setObj = {11, 33, 44, 77};

    for (std::set<int>::iterator it = setObj.begin(); it != setObj.end(); ++it) 
    {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    return 0;
}

Output:

11 33 44 77 

This will print all elements in the set in sorted order.

Unlike other containers, the values in the set are constant. Therefore, when accessing them through iterators, you cannot change the values of the set. This ensures that the uniqueness and the sorting order of the values in the set are preserved. If you attempt to modify any value using an iterator in the set, it will result in a compiler error. Let’s see an example where we will initialize a set of integers, fetch the iterator pointing to the first element of the set, and then try to change its value. In that case, we will get a compile error.

// Trying to modify a set value through
// an iterator (this will cause an error)
*it = 10;

Iterate over Set Using a Range-Based For Loop

C++11 introduced the range-based for loop. It’s a more concise way to iterate over all the elements of a container. We can also use it to iterate over all elements of a set. It does not require iterators. In the following example, we iterate over all the elements of a set of integers, printing them on the console one by one.

#include <iostream>
#include <set>

int main()
{
    std::set<int> setObj = {11, 33, 44, 77};

    for (const int &num : setObj)
    {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

Output:

11 33 44 77 

This will print all elements in the set, just like our earlier loop with iterators, but with cleaner syntax.

Summary

Iterating over sets in C++ is streamlined with the use of iterators and range-based for loops. While the constant nature of set iterators ensures data integrity, understanding these iteration techniques is key to effectively navigating and utilizing the set container.

Ritika Ohri

Hi, I am Ritika Ohri, founder of this blog. I craft comprehensive programming tutorials and also manage a YouTube channel. You can also connect with me on Linkedin.

Leave a Reply

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