8
$\begingroup$

Another design decision that baffled me. Checking if an element is in a set is the entire purpose of a set! Until C++20 I had to write stuff like s.find(x) != s.end() or the nicer s.count() cast as a bool that's almost as good as contains() but somewhat obscures the intent (and runs in O(n) for multisets?). Even if the standard library containers were designed around iterators, count() has existed from the beginning.

The P0458 proposal to add contains is obvious, but there must've been some kind of argument for leaving it out originally and then leaving it out every time it was brought up. Was there some kind of design philosophy change in C++20?

$\endgroup$

1 Answer 1

7
$\begingroup$

Because they wanted all containers to adhere to the same interface as much as possible, and .count() made sense for more containers, and still worked equivalently for set. They didn't want to break interface uniformity just for clearer semantics in one case.

Later on that decision was re-evaluated.

Also, the lack was not really much of a lack, since you can say if (myset.count(x)) just the same as you'd say if (myset.contains(x)). In modern times, more people run tools that complain about treating ints as bools, so that's become less attractive.

$\endgroup$
3
  • 6
    $\begingroup$ multiset.count(x) will take longer than contains $\endgroup$
    – qwr
    Commented Jul 20 at 0:18
  • 1
    $\begingroup$ @qwr So for multiset you'd use the .find() idiom. $\endgroup$
    – Barmar
    Commented Jul 20 at 3:55
  • 2
    $\begingroup$ Even if count and contains had the same cost for the container, it would be confusing to do this, because you would need to be aware that it has the same cost in that case. For most containers, you really wouldn't realize a logical contains call with an actual count call. $\endgroup$
    – feldentm
    Commented Jul 20 at 6:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .