std::unordered_map contains() 方法
- 自 C++20 起
// (1) Const version only
bool contains( const Key& key ) const;
// (2) Const version only
template< class K > bool contains( const K& x ) const;
- (1) 检查容器中是否存在键等同于
key
的元素。 - (2) 检查是否存在一个键与值
x
等价的元素。此重载仅在Hash::is_transparent
和KeyEqual::is_transparent
有效并各自表示一个类型时才参与重载解析。这假设这样的Hash
可以同时使用K
和Key
类型调用,并且KeyEqual
是透明的,这共同允许在不构造Key
实例的情况下调用此函数。
参数
key
- 要计数的元素的键值x
- 可以与键透明比较的任何类型的值
返回值
如果存在此类元素,则为 true
,否则为 false
。
复杂度
平均情况,常数 - O(1)。
最坏情况,与容器大小呈线性关系 - O(size())。
异常
(无)
示例
Main.cpp
#include <iostream>
#include <unordered_map>
int main()
{
std::unordered_map<int,char> example = {{1,'a'},{2,'b'}};
for(int x: {2, 5}) {
if(example.contains(x)) {
std::cout << x << ": Found\n";
} else {
std::cout << x << ": Not found\n";
}
}
}
输出
2: Found
5: Not found