Modify elements while Iterating over a Set in C++

This tutorial will discuss how to modify elements while iterating over a set in C++.

A set contains only unique elements. Moreover, the values in the set act as keys. Once an element is inserted into the set, its value cannot be changed. Modifying its value could disrupt the internal ordering of elements in the set. Therefore, in a set, we’re not permitted to change or update the values of already added elements. However, if you wish to modify the value of an existing element, you must first remove that element from the set and then insert the new (replacement) value.

For instance, consider a scenario where we iterate over all elements of a set. If any value matches our given criteria, we might want to replace it with a different value.

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

int value = 44;
int replacement = 33;

// Iterate over all elements of set
for (auto it = numbers.begin();
        it != numbers.end();
        it++ )
{
    // Check if iterator is pointing to given value
    if(*it == value)
    {
        // Remove the element from Set
        it = numbers.erase(it);

        // Insert the replacement value in set
        numbers.insert(replacement);
    }
}

Output:

21 22 23 33 45 60

Given that direct updates are prohibited, our approach involves removing the old value and inserting the new one. However, it’s crucial to note that when we erase an element from the set using the erase function, all existing iterators become invalidated. After calling the erase function, it returns an iterator pointing to the next valid element. Therefore, we must re-initialize our iterator in the for loop after erasing the element, and then proceed to insert the replacement value.

In the following example, assume we have a set of integers and aim to replace the value 44 with 33. To do so, we’ll remove the 44 element from the set and insert 33 in its place.

Let’s see the complete example,

#include <iostream>
#include <set>

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

    int value = 44;
    int replacement = 33;

    // Iterate over all elements of set
    for (auto it = numbers.begin();
         it != numbers.end();
         it++ )
    {
        // Check if iterator is pointing to given value
        if(*it == value)
        {
            // Remove the element from Set
            it = numbers.erase(it);

            // Insert the replacement value in set
            numbers.insert(replacement);
        }
    }

    // Print set contents
    for (auto x: numbers)
    {
        std::cout<< x << " ";
    }
    std::cout<< std::endl;

    return 0;
}

Output

21 22 23 33 45 60

Summary

Today, we learned how to modify elements while iterating over a set in C++.

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