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

蓝咒 提交于 2019-12-01 00:36:19

问题


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()?


回答1:


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).




回答2:


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.




回答3:


It's a standard operation on containers that returns the number of matching elements. In things like lists, this makes perfect sense. It just so happens that on a set, there can only be one occurrence of an element and therefore count can never return a value greater than 1.



来源:https://stackoverflow.com/questions/16534931/why-is-the-c-stl-set-containers-count-method-thus-named

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!