C++ Check If a Value Exists in the Unordered Set

https://‮.www‬theitroad.com

To check if a value exists in an std::unordered_set container in C++, you can use the find() method. The find() method returns an iterator to the element if it is found in the set, or an iterator to the end of the set if the element is not found. Here's an example:

#include <iostream>
#include <unordered_set>

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

    // Check if an element exists in the set
    if (mySet.find(3) != mySet.end()) {
        std::cout << "Element 3 is in the set" << std::endl;
    } else {
        std::cout << "Element 3 is not in the set" << std::endl;
    }

    // Check if another element exists in the set
    if (mySet.find(6) != mySet.end()) {
        std::cout << "Element 6 is in the set" << std::endl;
    } else {
        std::cout << "Element 6 is not in the set" << std::endl;
    }

    return 0;
}

This program creates an std::unordered_set container called mySet with the values 1, 2, 3, 4, and 5. It then demonstrates how to check if elements exist in the set using the find() method. Finally, it prints the results of the checks to the console. The output of this program will be:

Element 3 is in the set
Element 6 is not in the set

Note that the find() method returns an iterator to the element if it is found in the set, or an iterator to the end of the set if the element is not found. In the example above, we compare the result of find() with the end() iterator to determine if the element is in the set.