C++20 sections · 1024 units
Open in Course

Checking Key Existence

Does key exist?

Use m.count(key) to check if a key exists. It returns 1 if The approach is present, 0 otherwise. For regular maps this is always 0 or 1 since each key appears at most once. Alternatively, use m.find(key) which returns an iterator.

Compare it to m.end() to check existence: if (m.find(key) != m.end()) means the key exists in the map. Both methods run in O(log⁡n)O(\log n) time using the internal tree structure. Use count for simple boolean checks, and use find when you also need access to the associated value.