为什么std :: set没有“包含"?成员函数?
我正在大量使用std::set<int>
,通常我只需要检查这样的集合是否包含数字.
I'm heavily using std::set<int>
and often I simply need to check if such a set contains a number or not.
我觉得很自然地写:
if (myset.contains(number))
...
但是由于缺少contains
成员,我需要编写繁琐的代码:
But because of the lack of a contains
member, I need to write the cumbersome:
if (myset.find(number) != myset.end())
..
或不那么明显:
if (myset.count(element) > 0)
..
做出此设计决定的理由吗?
Is there a reason for this design decision ?
我认为这可能是因为他们试图使std::set
和std::multiset
尽可能相似. (显然,count
对std::multiset
具有完全明智的含义.)
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.
如果您假装count
只是contains
的拼写错误并将测试写为:
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))
...
虽然还是很遗憾.