c++stlstdset

Why does std::set not have a "contains" member function?


I'm heavily using std::set<int> and often I simply need to check if such a set contains a number or not.

I'd find it natural to write:

if (myset.contains(number))
   ...

But because of the lack of a contains member, I need to write the cumbersome:

if (myset.find(number) != myset.end())
  ..

or the not-as-obvious:

if (myset.count(element) > 0) 
  ..

Is there a reason for this design decision?


Solution

  • I think it was probably because they were trying to make std::set and std::multiset as similar as possible. (And obviously count has a perfectly sensible meaning for std::multiset.)

    Personally I think this was a mistake.

    It doesn't look quite so bad if you pretend that count is just a misspelling of contains and write the test as:

    if (myset.count(element)) 
       ...
    

    It's still a shame though.