Lesson Introduction

Hey there! Today, we're exploring sets in C++ — a useful way to handle collections of unique items. By the end of this lesson, you’ll know how to define sets, add and remove items, check for specific items, and iterate through all the items in a set. Let's dive in!

Understanding Sets in C++

A set in C++ is a container holding unique elements, just like a stamp collection without duplicates. Sets are perfect for tracking unique items without worrying about duplicates — like a class attendance list ensuring no name repeats.

To use sets in C++, include the set library with this line:

#include <set>
Defining a Set

To create an empty set that stores integers, define it like this:

#include <set>

std::set<int> mySet;

This declares a set named mySet for integers.

Adding Elements

Add elements using the insert function:

#include <set>
#include <iostream>

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

    mySet.insert(10);
    mySet.insert(20);
    mySet.insert(30);

    return 0;
}

If you try to insert 10 again, it won't be added as it’s a duplicate.

mySet.insert(10); // Duplicate, won't be added

However, it won't cause any errors.

Removing Elements

Remove an item with the erase function:

#include <set>
#include <iostream>

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

    mySet.insert(10);
    mySet.insert(20);
    mySet.insert(30);

    // Remove element 20
    mySet.erase(20);

    return 0;
}
Checking for Elements: `find` Function

Use find to check if an element is in the set. Find is a complex function that returns a thing called iterator pointing to the set's element. We will cover the details of it in the "Intermediate Programming in C++" path. By now, let's just say that if the find method doesn't find the element, it returns a thing which is equal to set.end(), so here is how we can make the comparison:

#include <set>
#include <iostream>

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

    mySet.insert(10);
    mySet.insert(20);
    mySet.insert(30);

    // Check if 10 is in the set
    if (mySet.find(10) != mySet.end()) {
        std::cout << "10 is in the set" << std::endl;  // Output: 10 is in the set
    }

    return 0;
}

It works, but seems a bit tricky and hard to remember, right? Let's try out another approach!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal