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 <unordered_set>
#include <string>

int main() {
    std::unordered_set<std::string> fruits;

    // Inserting elements
    fruits.insert("apple");
    fruits.insert("banana");
    fruits.insert("cherry");
    fruits.insert("apple"); // Duplicate, won't be inserted

    // Printing the set
    std::cout << "Fruits in the set:" << std::endl;
    for (const auto& fruit : fruits) {
        std::cout << fruit << std::endl;
    }

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

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

    // Removing an element
    fruits.erase("cherry");

    return 0;
}
Back to std_unordered_set