C++ Sets and Their Operations

Introduction

I'm delighted to welcome you to our C++ Sets lesson! Remember, std::set in C++ is similar to sets in other programming languages. It is a container that stores unique elements, following a specific order. They're especially useful when you need to ensure that elements in a collection appear only once.

In this lesson, you'll consolidate your knowledge of creating and operating on sets using std::set. You will learn about immutable sets concepts through const correctness and discover how sets enhance performance. Ready, set, go!

Creating and Manipulating Sets

Let's begin by creating a set in C++. It can be done using the std::set from the C++ Standard Library.

#include <iostream>
#include <set>

int main() {
    // Creating a set and printing it
    std::set<int> my_set = {1, 2, 3, 4, 5, 5, 5};  // Duplicates will be omitted
    for(const auto& elem : my_set)
        std::cout << elem << " ";  // Output: 1 2 3 4 5
    std::cout << std::endl;

    return 0;
}

C++ provides methods to manipulate sets, such as insert(), find(), erase(), and clear().

#include <iostream>
#include <set>

int main() {
    std::set<int> my_set = {1, 2, 3, 4, 5};

    // Adding an element
    my_set.insert(6);  // my_set is now {1, 2, 3, 4, 5, 6}
    
    std::cout << (my_set.find(1) != my_set.end()) << std::endl;  // Output: 1 (true), as my_set includes an element 1

    // Removing an element by key
    my_set.erase(1);  // my_set becomes {2, 3, 4, 5, 6}
    
    std::cout << (my_set.find(1) != my_set.end()) << std::endl;  // Output: 0 (false), as my_set doesn't include 1 anymore
    
    // Removing an element by iterator
    auto it = my_set.find(2);
    if (it != my_set.end()) {
        my_set.erase(it);  // my_set becomes {3, 4, 5, 6}
    }

    // Discarding an element (no function needed, erase does nothing if element doesn't exist)
    my_set.erase(7);  // No changes - 7 doesn't exist in my_set

    // Clearing the set
    my_set.clear();  // my_set becomes empty

    return 0;
}

Both erase() methods can be used for removing elements from a set, but they behave slightly differently depending on their parameters:

  • erase(iterator): Erases an element by iterator.
  • erase(key): Erases elements by key. If the element is not found, it does nothing.

In addition to std::set, the C++ Standard Library also includes std::unordered_set, which is similar in functionality but differs in terms of element ordering. Unlike std::set, std::unordered_set does not maintain any specific order for its elements.

The methods discussed above for std::set such as insert(), find(), erase(), and clear() also apply to std::unordered_set. This makes std::unordered_set a convenient choice when order is not important and you want to prioritize faster average membership tests.

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