example1_basic_usage.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <set>
#include <string>

int main() {
    std::set<int> numbers = {5, 2, 8, 1, 9, 3, 7};

    // Inserting elements
    numbers.insert(4);
    numbers.insert(6);
    numbers.insert(2); // Duplicate, won't be inserted

    // Printing the set
    std::cout << "Numbers in the set:" << std::endl;
    for (const auto& num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    // Checking if an element exists
    if (numbers.find(5) != numbers.end()) {
        std::cout << "5 is in the set" << std::endl;
    }

    // Removing an element
    numbers.erase(3);

    // Size of the set
    std::cout << "Number of elements: " << numbers.size() << std::endl;

    return 0;
}
Back to std_set