I can understand that multiset has count(), for counting the number of occurrences of a value, because elements can be repeated in multiset. But what's the point of having count() in set, when all the values are already unique?
Asked
Active
Viewed 1,682 times
1 Answers
17
count
is part of the associative container requirements(1).
Every associative container is required to provide it as part of its interface, even if the result is always zero or one as is the case with std::set
.
(1) This is a link to the SGI STL documentation describing the Associative Container concept; the concept as defined in the C++ standard may differ slightly, but not substantially.

James McNellis
- 348,265
- 75
- 913
- 977
-
Hmm...a compulsory requirement for a non-functional purpose. They could've implemented it with an empty body for set. Strange... – Nav Dec 03 '10 at 07:49
-
3@Nav: It cannot be implemented with an empty body for `std::set` because it must test whether the element exists in the set. It could be implemented in terms of `std::set::find`, though (`return find(k) != end() ? 1 : 0;`). It's not nonsensical; even for `std::set` it tells you how many elements with the given key exist in the container; it just happens that for `std::set`, the answer is always zero or one. – James McNellis Dec 03 '10 at 07:53
-
2Worth noting that by having more commonality in the interface it's easier to write higher level algorithms that can work with any of the containers, and easier to change code hardcoding one container to use another. Only makes sense when operations are semantically similar though, which is why the STL doesn't go out of its way to make dissimilar containers' interfaces similar. – Tony Delroy Dec 03 '10 at 07:53
-
@Tony: I agree, going from `set` to `multiset` (or the reverse) is easy thanks to their common interface. – Matthieu M. Dec 03 '10 at 08:17