Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the C++ STL set container's count() method thus named?

What it really checks for is contains() and not the count of the number of occurrences, right? Duplicates are not permitted either so wouldn't contains() be a better name than count()?

like image 737
Cricketer Avatar asked May 14 '13 04:05

Cricketer


2 Answers

It's to make it consistent with other container classes, given that one of the great aspects of polymorphism is to be able to treat different classes with the same API.

It does actually return the count. The fact that the count can only be zero or one for a set does not change that aspect.

It's not fundamentally different to a collection object that only allows two things of each "value" at the same time. In that case, it would return the count of zero, one or two, but it's still a count, the same as with a set.

The relevant part of the standard that requires this is C++11 23.2.4 which talks about the associative containers set, multiset, map and multimap. Table 102 contains the requirements for these associative containers over and above the requirements for "regular" containers, and the bit for count is paraphrased below:

size_type a.count(k) - returns the number of elements with key equivalent to k. Complexity is log(a.size()) + a.count(k).

like image 169
paxdiablo Avatar answered Oct 20 '22 10:10

paxdiablo


All associative containers must meet the requirements listed in §23.2.4/8 Table 102 - Associative container requirements. One of these is that they implement a.count(k) which then

returns the number of elements with key equivalent to k

So the reason is to have a consistent interface between all associative containers. For instance, this uniformity will be very important when writing generic function templates that must work with any associative container.

like image 30
Praetorian Avatar answered Oct 20 '22 10:10

Praetorian