Checking if a Key Exists without Inserting
How can I check if a key exists in a std::unordered_set
without inserting it if it doesn't?
To check if a key exists in a std::unordered_set
without inserting it if it doesn't, you can use the find()
method. The find()
method searches for an element with a specific key and returns an iterator to it if found, or an iterator to end()
if not found.
Here's an example:
#include <iostream>
#include <unordered_set>
int main() {
std::unordered_set<int> Set{1, 2, 3, 4, 5};
int Key = 3;
auto it = Set.find(Key);
if (it != Set.end()) {
std::cout << "Key " << Key
<< " exists in the set\n";
} else {
std::cout << "Key " << Key
<< " does not exist in the set\n";
}
Key = 7;
it = Set.find(Key);
if (it != Set.end()) {
std::cout << "Key " << Key
<< " exists in the set\n";
} else {
std::cout << "Key " << Key
<< " does not exist in the set\n";
}
}
Key 3 exists in the set
Key 7 does not exist in the set
In this example:
- We create an unordered set
Set
with some initial elements - We use
find()
to search for the key3
in the set. Since3
exists,find()
returns an iterator to the element. - We compare the returned iterator with
Set.end()
to determine if the key was found. If the iterator is not equal toSet.end()
, it means the key exists in the set. - We then search for the key
7
, which doesn't exist in the set. In this case,find()
returns an iterator equal toSet.end()
, indicating that the key was not found.
Using find()
allows you to check for the existence of a key without modifying the set. If the key is not found, no insertion takes place.
Note that if you want to insert the key if it doesn't exist, you can use the insert()
method instead. The insert()
method returns a pair containing an iterator to the inserted element (or the existing element if the key already exists) and a boolean value indicating whether the insertion took place.
Hash Sets using std::unordered_set
This lesson provides a thorough understanding of std::unordered_set
, from basic initialization to handling custom types and collisions