C++

Create a STD Set in C++

A set in C++ is very similar to a set in Mathematics. The following is a set of integers:

{-5, 6, 9, 8, -2}

The following is a set of characters:

{'B', 'M', 'A', 'C', 'T', 'O', 'Q'}

The following is a set of strings (items on a reading table):

{"reading lamp", "computer", "pen", "pencil", "exercise books", "text books"}

In C++, each value in each of the above sets, is called a key.

In C++, a set does not allow duplicate values. However, still in C++, a multiset allows duplicate values. This article addresses set, and does not address multiset.

STD means Standard. This article is on how to create a standard set in C++. Adding elements (values) into the set, is also mentioned.

Library

C++ has one main library, called the C++ Standard Library. This library has sub libraries that are also divided into further sub libraries which are divided further into more sub libraries. The bottom sub-libraries can be seen as modules. The first level sub-library of interest here is called the Containers Library. The Containers Library has a sub-library, called the Associative Containers Library. The Associative Containers Library has a sub-library called the set library. This set library can be considered as a module. In order to code sets, it has to be included at the beginning of the program as follows:

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

iostream should always be included if the terminal (console) is to be used for output (and input). The second line in this code segment includes the set module. The third line is a statement ending with a semicolon, the insists on the use of the standard namespace.

In order to compile the program, with the g++20 compiler for C++ 20, use the following command:

g++ -std=c++2a filename.cpp -o filename

Run the program with:

./filename

assuming that the compiled file is in the user (home) directory.

Constructing a Set

Constructing or creating a set is the main issue of this article. There are many constructors for the set. Only the most commonly used will be explained here.

Constructing an Empty Set

The following statement will construct an empty set:

set<int> st;

It begins with the class type. This is followed by angle brackets, which has the type for the elements (values). There is a space and then the name of the set (st).

Inserting Values

Elements can be inserted with the insert() method of the set class, as follows:

set<int> st;
st.insert(-5); st.insert(6); st.insert(9);
st.insert(8); st.insert(-2);

The set {-5, 6, 9, 8, -2} has been inserted.

Returning an Iterator

The set class does not have the square brackets operator, like the array. So, to scan the elements of the set, an iterator is needed. If the name of the set is st, then the following statement will return an iterator that points to the first element of the set:

set<int>::iterator iter = st.begin();

Appreciate the syntax of this statement.

Size of the Set

The following statement returns the size of a set:

int sz = st.size();

The variable, sz, holds the size of the set.

Reading Values of the Set

The following program uses the iterator to read all the values in the set:

set<int> st;
st.insert(-5); st.insert(6); st.insert(9);
st.insert(8); st.insert(-2);

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

The output is:

-5, -2, 6, 8, 9,

Note how the for-loop and the iterator were used. “st.end()” returns the end iterator which points just after the last element.

With strings as elements, the string module has to be included with;

#include <string>

Consider the following code with string elements:

set<string> st;
st.insert("reading lamp"); st.insert("computer"); st.insert("pen");
st.insert("pencil"); st.insert("exercise books"); st.insert("text books");

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

The output is:

computer, exercise books, pen, pencil, reading lamp, text books,

Note that when values are added with the insert() command, the set is sorted internally.

Note also 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(const set& x)
This is a set constructor, that would take the identifier of another set as argument, to construct a new set. The following code illustrates this:

set st;
st.insert(-5); st.insert(6); st.insert(9); st.insert(8); st.insert(-2);

set<int> st2(st);

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

The output is:

-5, -2, 6, 8, 9,

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

This is a constructor, where the second and third arguments are optional. When not given, the default values are chosen by C++. The first argument is an initializer_list (array literal). The following code illustrates the use of the constructor:

set<char> st({'B', 'M', 'A', 'C', 'T', 'O', 'Q'});

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

The output is:

A, B, C, M, O, Q, T,

Notice that the output is sorted despite the fact that the input is an unsorted initializer_list.

Note: With the initializer_list, the parentheses of the constructor call, may be omitted, as in the following code:

set<char> st{'B', 'M', 'A', 'C', 'T', 'O', 'Q'};

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

The output is still:

A, B, C, M, O, Q, T,

Copy Constructors

A set can be created by assigning the identifier of another set to the identifier of the new set, or by assigning the literal set (array literal) to the identifier of the new set.

set& operator=(const set& x)
This assigns the identifier of another set to the identifier of a new set as shown, thus:

set<char> st;
st.insert('B'); st.insert('M'); st.insert('A'); st.insert('C');
st.insert('T'); st.insert('O'); st.insert('Q');

set<char> st2 = st;

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

The output is:

A, B, C, M, O, Q, T,

set& operator=(initializer_list<value_type>)
This assigns the literal set (array literal) to the identifier of a new set as shown, thus:

set<char> st = {'B', 'M', 'A', 'C', 'T', 'O', 'Q'};

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

The output is:

A, B, C, M, O, Q, T,

Conclusion

The set literal in C++ is similar to that of mathematics. A set, which is not sorted becomes sorted, ascending, after construction (creation) with the default settings. STD means Standard. The common ways of creating a set has been illustrated above.

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.