std::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
比较等价的元素。此重载仅当限定 IDCompare::is_transparent
有效且表示一个类型时才参与重载解析。它允许在不构造Key
实例的情况下调用此函数。
参数
key
- 要计数的元素的键值x
- 可以与键透明比较的任何类型的值
返回值
如果存在此类元素则为 true
,否则为 false
。
复杂度
对容器大小呈对数关系 - O(log size())。
异常
(无)
示例
Main.cpp
#include <iostream>
#include <map>
int main()
{
std::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