C++20 sections · 1024 units
Open in Course

Checking Membership

Is element present?

Use s.count(value) to check if an element exists. It returns 1 if present, 0 if not. For regular sets this is always 0 or 1 since duplicates aren't allowed. Or use s.find(value) != s.end() to check membership.

The find method returns an iterator that you can also use to access the element or erase it later. C++20 adds s.contains(value) which returns a bool directly. This is the clearest syntax if your compiler supports C++20.

All these operations run in O(logn)O(\log n) time.