In this article, we will discuss how to add elements to a set in C++ and what happens when we try to insert duplicate elements in a Set.

A set is an associative container provided by STL in C++. It keeps only unique elements and stores them in sorted order. It supports fast searching with a time complexity of O(log n).

Inserting Elements to Set Using the insert() Function

The set class provides a member function insert() to add elements to the set object. Although the insert() function adds elements to the set, elements are stored in sorted order. Additionally, it will not add an element if an element with the same value already exists in the set.

Let’s see an example where we create an empty set and then add three elements to it using the insert() function.

#include <iostream>
#include <set>

int main()
{
    std::set<int> setObj;

    // Inserting elements
    setObj.insert(41);
    setObj.insert(32);
    setObj.insert(12);
    setObj.insert(34);

    // Printing the size of the set
    std::cout << "Size of set: " << setObj.size() << std::endl;

    // Using range-based for loop to print set contents
    // This will print: 12 32 34 41
    for (int num : setObj)
    {
        std::cout << num << " ";
    }

    return 0;
}

Output:

12 32 34 41

Here, we created an empty set and then added 4 elements to it. The set class also provides a function size(), which returns the number of elements in the set. In our case, it returned 4. Then we used the range-based for loop to iterate over the set elements and print them one by one.

Range-based For Loop was introduced in C++11, allowing for easier iteration over collections. It’s a simpler way to iterate over all the elements of a container. Instead of using the traditional for loop, the range-based for loop automatically goes through each element in the collection, making the code cleaner and more readable. We will discuss it further in a later section of this series.

Inserting Duplicate Elements in Set

Since a set can store only unique elements, if we try to insert any duplicate value into the set using the insert() function, it won’t be allowed. Basically, if the given value is a duplicate, the insert() function will skip the insertion.

The insert() function returns a pair, where the first value in the pair is an iterator pointing to the inserted element (or to the existing element that prevented the insertion). The second item is a boolean indicating whether the insertion was successful or not.

Let’s see an example:

#include <iostream>
#include <set>

int main()
{
    // Creating an empty Set
    std::set<int> setObj;

    // Insert value 4 in the set
    auto result = setObj.insert(4);

    // Check if insertion was successful
    if (result.second)
    {
        std::cout << "Inserted successfully." << std::endl;
    }
    else
    {
        std::cout << "Insertion failed. Duplicate value." << std::endl;
    }

    // Attempting to insert a duplicate value
    result = setObj.insert(4);

    // Check if insertion was successful
    if (result.second)
    {
        std::cout << "Inserted successfully." << std::endl;
    }
    else
    {
        std::cout << "Insertion failed. Duplicate value." << std::endl; // This line will execute
    }

    return 0;
}

Output:

Inserted successfully.
Insertion failed. Duplicate value.

In the example above, we created an empty set and then inserted the value 4 into the set using the insert() function. We then checked if the insertion was successful or not. After that, we attempted to insert the value 4 again into the set. This time, the insertion failed because a set cannot contain duplicate values.

Summary

In this article, we learned how to insert elements in a Set in C++.

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.