Insert elements to Set in C++

In this article, we will discuss different ways to insert elements in a Set in C++.

The set container in C++ offers three distinct overloaded versions of the insert() member function to add elements. Let’s delve into each version.

Insert Single Element to Set in C++

A set is an associative container that contains only unique elements. As such, an insertion attempt can fail if a similar element already exists in the set. With this in mind, set offers a particular version of the insert() function, which is:

pair<iterator,bool> insert (const value_type& val);

It accepts the element intended for insertion and returns a pair consisting of an Iterator and a bool flag.

If the insertion is successful, the bool flag in the returned pair will be set to true, and the iterator will point to the newly inserted element. However, if the insertion fails due to the presence of a duplicate element, the bool flag in the returned pair will be set to false.

Suppose we have a set of strings i.e.

std::set<std::string> setOfStrs;

Now let’s insert an element to the Set using the insert() i.e.



    // A pair of set iterator and bool
    std::pair<std::set<std::string>::iterator, bool> result;
    
    // Insert Returns a pair of iterator and bool
    result = setOfStrs.insert("Hi");
    
    // Check if element added sucessfuly
    if (result.second)
    {
        std::cout << "String 'Hi' Inserted successfully in Set \n";
    }
    

    It will insert the provided string into the set. Since the set was initially empty, the insertion will be successful. As a result, it will return a pair containing a true value and an iterator pointing to the newly inserted element.

    Check out complete example as follows,

    #include <iostream>
    #include <set>
    #include <iterator>
    #include <string>
    
    void addToSet(std::set<std::string> &setOfStrs, std::string str)
    {
        // A pair of set iterator and bool
        std::pair<std::set<std::string>::iterator, bool> result;
    
        // Insert Returns a pair of iterator and bool
        result = setOfStrs.insert(str);
    
        // Check if element added sucessfuly
        if (result.second)
            std::cout << str << " - Inserted sucessfuly" << std::endl;
        else
            std::cout << str << " - Not Inserted sucessfuly" << std::endl;
    }
    
    int main()
    {
        std::set<std::string> setOfStrs;
    
        addToSet(setOfStrs, "Hi");
    
        // Try to insert the duplicate element.
        addToSet(setOfStrs, "Hi");
    
        addToSet(setOfStrs, "the");
        addToSet(setOfStrs, "is");
        addToSet(setOfStrs, "Hello");
    
        std::cout << "**Set Contents***" << std::endl;
    
        for (auto elem : setOfStrs)
            std::cout << elem << std::endl;
    
        return 0;
    }
    

    Output:

    Hi - Inserted sucessfuly
    Hi - Not Inserted sucessfuly
    the - Inserted sucessfuly
    is - Inserted sucessfuly
    Hello - Inserted sucessfuly
    **Set Contents***
    Hello
    Hi
    is
    the
    

    Insert Multiple Elements to Set from another Container in C++

    The std::set class in C++, offers another overloaded version of the insert() function:

    template <class InputIterator>
    void insert (InputIterator first, InputIterator last);
    

    This function takes a range of input iterators and inserts each element into the set while traversing through the range (from first up to, but not including, last).

    In the following example, we insert elements from a vector into a set by providing the vector’s iterator range to the insert() function:

    #include <iostream>
    #include <set>
    #include <iterator>
    #include <string>
    #include <vector>
    
    int main()
    {
        // Create & Initialize a Vector of Strings
        std::vector<std::string> vecOfStrs = 
                            {"Hi", "Hello", "is", "the", "at", "Hi", "is"};
    
        // A Set of Strings
        std::set<std::string> setOfStrs;
    
        // Insert a Range in set
        // Range here is start and end iterators of a vector
        setOfStrs.insert(vecOfStrs.begin(), vecOfStrs.end());
    
        // It will insert all the elements in vector to set, but as
        // set contains only unique elements, so duplicate elements will
        // be automatically rejected.
    
        // But there is no way to find out how many actually inserted
        // because it doesn't return any value.
    
        std::cout<<"**Set Contents***"<<std::endl;
    
        for(auto elem : setOfStrs)
            std::cout<<elem<<std::endl;
    
        return 0;
    }
    

    Output:

    **Set Contents***
    Hello
    Hi
    at
    is
    the
    

    The insert() function only adds unique elements to the set and discards the duplicates. Since this version of the overloaded insert() function doesn’t return any value, we don’t have information post-call about which elements were successfully inserted and which were rejected.

    Similarly, we can insert elements from other containers by supplying a range of iterators to the insert() function.

    Insert Multiple elements to set using Initializer List in C++

    The std::set offers another variant of the insert() function which accepts an initializer list:

    void insert (initializer_list<value_type> il);
    

    This version allows for a direct insertion of elements from an initializer list into the set.

    For instance, consider this example where we insert elements using an initializer list:

    std::set<int> setObj;
    setObj.insert({1, 2, 3, 4, 5});
    
    // setObj now contains: 1, 2, 3, 4, 5
    

    This method simplifies the process of adding multiple elements to a set in one go.

    Checkout the complete example below, where we are inserting elements from an initiazer list to the set i.e.

    #include <iostream>
    #include <set>
    #include <iterator>
    #include <string>
    
    int main()
    {
        // Create an empty Set of  Strings
        std::set<std::string> setOfStrs;
    
        // Insert a Initializer list in the set
        setOfStrs.insert({"Hi", "Hello", "is", "the", "at", "Hi", "is"});
    
        // It will insert all the elements in initializer_list to set, but as
        // set contains only unique elements, so duplicate elements will
        // be automatically rejected.
    
        // But there is no way to find out how many actually inserted
        // because it doesn't return any value.
    
        std::cout<<"**Set Contents***"<<std::endl;
    
        for(auto elem : setOfStrs)
            std::cout<<elem<<std::endl;
    
        return 0;
    }
    

    Output:

    **Set Contents***
    Hello
    Hi
    at
    is
    the
    

    This version of the insert() function only adds unique elements to the set and disregards any duplicates. However, since this variant of insert() doesn’t return any value, we’re left uninformed about which specific elements were successfully inserted and which were rejected.

    Summary

    We learned about three different ways to insert elements into a Set in C++.

    Scroll to Top