7

I'm learning C++ and apparently a way of checking if a particular key exists in a std::map is using the member function count.

My first though was: Aren't the keys supposed to be unique? And checking the documentation indeed they are unique, so count will either return 0 or 1.

Isn't it a bit counter-intuitive to call it count? Why not exist?

To me count makes sense in a list where you expect a number of occurrences of an element, but if the method is only allowed to return 1 or 0 it doesn't make sense to me.

Am I missing something? Is there a reason to call it count or it's just a bad naming?

  • 7
    It is just for consistency with `std::multimap`. – JFMR Dec 04 '18 at 14:35
  • Are 0 and 1 not numbers of occurrences? – Eric Postpischil Dec 04 '18 at 14:36
  • 5
    All associative containers need to have `count`. It makes writing generic code easier. – NathanOliver Dec 04 '18 at 14:36
  • 5
    And you want the consistency because of duck-typing for templates, which doesn't work so well when everything quacks a little differently. – nwp Dec 04 '18 at 14:36
  • 3
    related/dupe: https://stackoverflow.com/questions/4343130/why-does-stl-set-have-count-when-all-elements-are-supposed-to-be-unique also https://stackoverflow.com/questions/16534931/why-is-the-c-stl-set-containers-count-method-thus-named also https://stackoverflow.com/questions/42532550/why-does-stdset-not-have-a-contains-member-function/42532783 – NathanOliver Dec 04 '18 at 14:38

2 Answers2

7

It's a little like using a method .numberOfWives() to determine if you are married or not. Does the job and helps build generic code.

Sure, it's normally 0 or 1 (std::map), but it could be more than one (std::multimap, or polygamous jurisdictions).

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 2
    Somewhat outdated and inaccurate though :) This should at least be locale-dependent I guess. – lubgr Dec 04 '18 at 14:44
  • 2
    @lubgr: Yes, consider refactoring to `.numberOfWives() + .numberOfHusbands()`; and consider the implications of unsigned type overflow. – Bathsheba Dec 04 '18 at 14:45
0

It is possible that the name count be unified with other containers, such as std::multimap and std::multisets.

snake_style
  • 1,139
  • 7
  • 16