Containers in Practice
Unordered Set Lookup
An unordered set answers membership questions without requiring the values to stay sorted.
unordered set
A `std::unordered_set` stores unique values and optimizes lookup instead of ordering.
contains
Before C++20, `find` is the common membership check for unordered sets.
Unordered Set Lookup
unordered_set_lookup.cpp
Replay: real traced execution (multi-file project)
#include <iostream>
#include <string>
#include <unordered_set>
int main() {
std::string role = "admin";
std::unordered_set<std::string> allowed{"admin", "editor"};
bool present = allowed.find(role) != allowed.end();
std::cout << "role=" << role << std::endl;
std::cout << "present=" << present << std::endl;
return 0;
}
#include <iostream>
#include <string>
#include <unordered_set>
int main() {
std::string role = "guest";
std::unordered_set<std::string> allowed{"admin", "editor"};
bool present = allowed.find(role) != allowed.end();
std::cout << "role=" << role << std::endl;
std::cout << "present=" << present << std::endl;
return 0;
}
#include <iostream>
#include <string>
#include <unordered_set>
int main() {
std::string role = "editor";
std::unordered_set<std::string> allowed{"admin", "editor"};
bool present = allowed.find(role) != allowed.end();
std::cout << "role=" << role << std::endl;
std::cout << "present=" << present << std::endl;
return 0;
}
role ← admin, allowed ← (empty), present ← 1
5int main() {6 std::string role→ admin = "admin"; //@role="guest", "editor"78 std::unordered_set<std::string> allowed→ (empty){"admin", "editor"};9 bool present→ 1 = allowed(empty).find(roleadmin) != allowed.end();1011 std::cout << "role=" << roleadmin << std::endl;12 std::cout << "present=" << present1 << std::endl;13 return 0;14}outputrole=admin present=1
role ← guest, allowed ← (empty), present ← 0
5int main() {6 std::string role→ guest = "guest";78 std::unordered_set<std::string> allowed→ (empty){"admin", "editor"};9 bool present→ 0 = allowed(empty).find(roleguest) != allowed.end();1011 std::cout << "role=" << roleguest << std::endl;12 std::cout << "present=" << present0 << std::endl;13 return 0;14}outputrole=guest present=0
role ← editor, allowed ← (empty), present ← 1
5int main() {6 std::string role→ editor = "editor";78 std::unordered_set<std::string> allowed→ (empty){"admin", "editor"};9 bool present→ 1 = allowed(empty).find(roleeditor) != allowed.end();1011 std::cout << "role=" << roleeditor << std::endl;12 std::cout << "present=" << present1 << std::endl;13 return 0;14}outputrole=editor present=1