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:
Set
with some initial elementsfind()
to search for the key 3
in the set. Since 3
exists, find()
returns an iterator to the element.Set.end()
to determine if the key was found. If the iterator is not equal to Set.end()
, it means the key exists in the set.7
, which doesn't exist in the set. In this case, find()
returns an iterator equal to Set.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.
Answers to questions are automatically generated and may not have been reviewed.
std::unordered_set
This lesson provides a thorough understanding of std::unordered_set
, from basic initialization to handling custom types and collisions