C++

Ways to Initialize a STD Set in C++

The following is the list of colors of the rainbow:

    {"red", "orange", "yellow", "green", "blue", "indigo", "violet"}

This is an example of a set literal in mathematics as well as in C++. It is also an array literal. It is a set of strings. Sets of integers, floats, doubles, etc., are also possible.

STD stands for Standard. This article is on ways to initialize a set as code. There is a set class in a module in the C++ standard library. Initialization here, means giving values to the set at the time of creation. Creating a set is constructing the set.

A set can be constructed with the initial values. A set can also be constructed empty and then the values inserted after creation.

The set module (sub library) has to be included into the program before a set object can be created and initializing it at the same time. A C++ program that involves sets should begin as follows:

    #include <iostream>
    #include <set>
    using namespace std;

The first line in this code segment includes the iostream (sub) library. If output (and input) is for the terminal (console), then the iostream library has to be included. The second line includes the set (sub) library; this is a must. The third line is not a directive; it is a statement. It insists that any name used without preceding it with a user namespace name is from the C++ standard namespace.

The rest of this article explains different ways of initializing the set during construction with the different construction methods. At the end of the article, adding (inserting) values to the empty set is addressed.

set(initializer_list<value_type>, const Compare& = Compare(), const Allocator& = Allocator())

This is a constructor to create a set. Its first argument is the set initializer_list. The initializer_list is the set literal. It is the same as the array literal. If the second and third arguments are not typed, then their default arguments will be employed. The following program shows this constructor in action with its initialization:

    #include <iostream>
    #include <set>
    #include <string>
    using namespace std;

    int main()
    {
        set st({"red", "orange", "yellow", "green", "blue", "indigo", "violet"});
        for (set::iterator iter = st.begin(); iter != st.end(); iter++)
            cout << *iter << ", ";
        cout << endl;
        return 0;
    }

The output is:

blue, green, indigo, orange, red, violet, yellow,

Notice that the output is sorted in ascending order, while the input (first argument) was not sorted.

Also note that to use strings, the string class has to be included; otherwise, it is the pointers to the strings that will be sorted, and not the string alphabetic literals themselves.

set& operator=(initializer_list<value_type>)

This is the copy constructor form of the above constructor. It still does initialization. The following program shows this constructor in action with its initialization:

    #include <iostream>
    #include <set>
    #include <string>
    using namespace std;

    int main()
    {
        set st = {"red", "orange", "yellow", "green", "blue", "indigo", "violet"};
        for (set::iterator iter = st.begin(); iter != st.end(); iter++)
            cout << *iter << ", ";
        cout << endl;
        return 0;
    }

The output is:

blue, green, indigo, orange, red, violet, yellow,

Notice that the output is sorted in ascending order, while the input (first argument) was not sorted.

set(const set& x)

This constructor creates a second set using the identifier of a previous set as argument. Immediately after the creation, there are two copies of the same content. The following program shows this constructor in action with its initialization:

    #include <iostream>
    #include <set>
    #include <string>
    using namespace std;

    int main()
    {
        set st = {"red", "orange", "yellow", "green", "blue", "indigo", "violet"};
        set st2(st); //initialization
        for (set::iterator iter = st2.begin(); iter != st2.end(); iter++)
            cout << *iter << ", ";
        cout << endl;
        return 0;
    }

The output is:

blue, green, indigo, orange, red, violet, yellow,

Notice that the output is sorted in ascending order, while the input (first argument) was not sorted.

set& operator=(const set& x)

This is a real copy constructor. It still does initialization. The following program shows this constructor in action with its initialization:

    #include <iostream>
    #include <set>
    #include <string>
    using namespace std;

    int main()
    {
        set st = {"red", "orange", "yellow", "green", "blue", "indigo", "violet"};
        set st2 = st; //initialization
        for (set::iterator iter = st2.begin(); iter != st2.end(); iter++)
            cout << *iter << ", ";
        cout << endl;
        return 0;
    }

The output is:

blue, green, indigo, orange, red, violet, yellow,

Notice that the output is sorted in ascending order, while the input (first argument) was not sorted.

template<class InputIterator> set(InputIterator first, InputIterator last, const Compare& comp = Compare(), const Allocator& = Allocator());

This constructor will create a new set by copying a range of values from another set. The range begins from the value pointed to by first, and to, but not including the value pointed to by last. If the other arguments for the constructor are not typed, their default arguments will be employed. The template argument is the iterator class. The following program shows this constructor in action with its initialization:

    #include <iostream>
    #include <set>
    #include <string>
    using namespace std;

    int main()
    {
        set st = {"red", "orange", "yellow", "green", "blue", "indigo", "violet"};
        set::iterator iterF = st.begin(); iterF++;
        set::iterator iterL = st.end(); iterL--;

        set st2(iterF, iterL); //initialization

        for (set::iterator iter = st2.begin(); iter != st2.end(); iter++)
            cout << *iter << ", ";
        cout << endl;
        return 0;
    }

The output is:

green, indigo, orange, red, violet,

which is not exactly what might have been expected. The reason is as follows:

The input is:

"red", "orange", "yellow", "green", "blue", "indigo", "violet"

So, it might have been expected that "red" and "violet" would be omitted. Instead, it was "blue" and "yellow" that were omitted. Now, when an unordered set is inputted into a set, it becomes sorted. From the sorted list, the values at the extreme ends, were omitted.

Empty Set and insert()

The following program creates an empty set before the values are inserted:

    #include <iostream>
    #include <set>
    #include <string>
    using namespace std;

    int main()
    {
        set st;
        st.insert("red"); st.insert("orange"); st.insert("yellow"); st.insert("green");
        st.insert("blue"); st.insert("indigo"); st.insert("violet");

        for (set::iterator iter = st.begin(); iter != st.end(); iter++)
            cout << *iter << ", ";
        cout << endl;
        return 0;
    }

The output is:

blue, green, indigo, orange, red, violet, yellow,

Notice that the output is sorted in ascending order, while the input (first argument) was not sorted.

Conclusion

Initialization is when values are added as the set is created. After this phase, the values become sorted ascending with default settings. The common ways to initialize a set in C++ involve conventional construction and copy construction. They have been explained above.

Chrys

About the author

Chrysanthus Forcha

Discoverer of mathematics Integration from First Principles and related series. Master’s Degree in Technical Education, specializing in Electronics and Computer Software. BSc Electronics. I also have knowledge and experience at the Master’s level in Computing and Telecommunications. Out of 20,000 writers, I was the 37th best writer at devarticles.com. I have been working in these fields for more than 10 years.