C++ Set Container

The Set Container is one of many C++ containers that are used to store data. Moreover, Set belongs to the sub-branch of Associative containers, which store data in a sorted order. This makes accessing and searching through the data faster, and the cost of inserting data taking longer.


Creating a Set Container

What makes the Set Container different from other Associative Containers is that it stores “unique and sorted” data. By unique, we mean there are no duplicates of the same data element in this container.

All container types in C++ are class templates, which means they are very flexible with what kind of data type that can store. Furthermore, this means they all have the same declaration method, making it easy to learn, remember and work with several container types.

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

int main() {
    set<int> s1 = {2, 1, 3, 8, 0};
    return 1;
}

The above code shows us to declare a set in C++. Make sure to include the <set> header file!

Working with Sets

Let’s try some basic methods and operations on the Set Container. We’ll also observe how the Set automatically handles data and removes duplicates when passing a random set of data to it.

    set<int> s1 = {2, 1, 3, 4, 0, 1};
    cout << "OUTPUT: " << s1.size() << endl;

    if (!s1.empty()) {
        for (int i: s1) {
            cout << i << endl;
        }
    }

Running the above code gives us the following output.

OUTPUT: 5
0
1
2
3
4

Notice how instead of 6 elements, which we originally entered, there are only 5. This is because a duplicate value was removed. We can also see from the output that the data is in sorted order.

Inserting Data

Now let’s take a look at adding data into the set using the insert() function. We’ve also used the empty() function which returns 1 or 0, depending on whether the set is empty or not.

    set<int> s1 = {2, 1, 3, 4, 0, 1};
    s1.insert(7);
    s1.insert(5);

    cout << "OUTPUT: " << s1.size() << endl;

    if (!s1.empty()) {
        for (int i: s1) {
            cout << i << endl;
        }
    }

The output shows the new size of the set after adding 2 elements, and the new sorted order.

OUTPUT: 7
0
1
2
3
4
5
7

Accessing Elements in a Set

One unique thing about the Set Container is that it does not have a subscript operator. This means you cannot do mySet[0] to access the first element. Rather, we must use a different concept called iterators.

The below code creates an iterator for the set container we just made. An iterator is basically a pointer that points to a value in the list. We need to provide it an initial value to point to, using begin() or end() methods.

The below code demonstrates the workings of the iterator, that after initializing it with begin(), printing it shows the value of the first element. Incrementing it will make it point to the next value, which in this case is 1.

    set<int> s1 = {2, 1, 3, 4, 0, 1};

    set<int>::iterator it = s1.begin();

    cout << *it << endl;
    it++;
    cout << *it << endl;

Output: (And remember, you need to de-reference it because it’s a pointer)

0
1

Let’s try another way of accessing elements, which may be familiar to those who have used Pointers alot. Since it, the iterator points to the first element in our below code, adding the number x should make it point to the x+1th value in the list.

    set<int> s1 = {2, 1, 3, 4, 0, 1};

    set<int>::iterator it = s1.begin();
    cout << *it + 3 << endl;

Output:

3

Advance()

There’s an alternate way of doing this that’s more recommended. It involves the use of the advance() function that performs the same task by taking two parameters, the iterator and the offset.

The equivalent to the above code:

    set<int> s1 = {2, 1, 3, 4, 0, 1};
    set<int>::iterator it = s1.begin();

    advance(s1, 3);
    cout << *it << endl;

You can also pass negative values into the advance function.

    set<int> s1 = {2, 1, 3, 4, 0, 1};
    set<int>::iterator it = s1.end();

    advance(s1, -3);
    cout << *it << endl;

Try running the above code!


Multi-Set Container

A multi-set container is pretty much the exact same thing as a set with one difference. Unlike a Set, a Multi-Set does not a duplicate filter, meaning it only stores sorted data, not “unique and sorted” data. Other than this, all methods and other related functions work in the exact same manner.

    multiset<int> ms1 = {4, 3, 4, 2, 1, 0 };

And of course, there is a slight syntax difference in the declaration.


Other Methods

find():This method returns a pointer to the set, pointing to a certain value which we pass into the find() function. It’s similar to begin() and end(), except you can pick which value you want it to point to.

int main() {
    set<int> s1 = {5, 2, 1, 9};

    set<int>::iterator ptr = s1.find(5);

    cout << *ptr << endl;

    return 1;
}

begin() and end(): We’ve already shown these before, so we’ll just explain them properly here. These two methods actually return pointers to the starting and ending of the Set respectively.

erase(): You can use this method to remove certain values from a Set Container.

int main() {
   set<int> s1 = {5, 2, 1, 9};

   s1.erase(2);

   if (!s1.empty()) {
        for(int i: s1) {
            cout << i << endl;
        }
   }
    return 1;
}
1
5
9

Remember, the value you pass into erase is the actual value you want to delete, not it’s index.

swap(): You can use the swap() method to completely swap the values of two sets with each other.

    set<int> s1 = {1, 2, 3};
    set<int> s2 = {4, 5, 6};

    s1.swap(s2);

Remember though, both of them must have the same datatype (int in this case), else there will be an error.


This marks the end of the C++ Set Container tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions you might have regarding the tutorial content can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments