How to Find with Hash Set
c++11
containers
intermediate
To find an element in a std::unordered_set
we use the find()
method.
The find()
method returns an iterator to a key, meaning an iterator to Key
.
If nothing was found, the end()
iterator is returned from the unordered_set.
#include <unordered_set> #include <string> #include <iostream> int main() { std::unordered_set<std::string> planets{ {"Venus"}, {"Earth"}, {"Mars"}, }; auto it = planets.find("Earth"); if (it != planets.end()) { std::cout << *it << "\n"; } else { std::cout << "No such planet.\n"; } it = planets.find("PlanetX"); if (it != planets.end()) { std::cout << *it << "\n"; } else { std::cout << "No such planet.\n"; } }
Earth No such planet.