P0458R0 Checking for Existence of an Element in Associative Containers

The paper proposes to add a member function contains, that checks, whether or not a given element exists in a container, to standard associative containers

The most common current idiom requires some boilerplate:

if (some_set.find(element) != some_set.end()) {
// ...
}
		
An alternative is using the count method. Downsides:

  • Does not express the intent as clearly as contains would. E.g., compare:
    if (str.size())   vs    if (!str.empty())
  • O(count(key)) for multiset/multimap

Qt associative containers implement contains. It is a more common operation than find. Estimate done by Thiago Macieira (for Qt codebase):

  • find: 553 occurrences
  • contains: 2977 occurrences

Design decisions

Straw poll: member function vs free function.

Considerations for the "free function" option:

  • Do we want it to work only for assciative containers or for arbitrary ranges as well
  • What about a pair of iterators