std::unordered_set<Key,Hash,KeyEqual,Allocator>::contains
来自 cppreference.cn
bool contains( const Key& key ) const; |
(1) | (C++20 起) |
template< class K > bool contains( const K& x ) const; |
(2) | (C++20 起) |
1) 检查容器中是否存在键等同于 key 的元素。
2) 检查是否存在键与值 x “等效”的元素。此重载仅在 Hash::is_transparent 和 KeyEqual::is_transparent 有效且各自表示一个类型时才参与重载决议。这假定此类
Hash
可以与 K
和 Key
类型一起调用,并且 KeyEqual
是透明的,这共同允许在不构造 Key
实例的情况下调用此函数。目录 |
[edit] 参数
key | - | 要搜索的元素的键值 |
x | - | 可与键透明比较的任何类型的值 |
[edit] 返回值
如果存在这样的元素则为 true ,否则为 false 。
[edit] 复杂度
平均情况下为常数时间,最坏情况下与容器大小成线性关系。
[edit] 示例
运行此代码
#include <iostream> #include <unordered_set> int main() { std::unordered_set<int> example{1, 2, 3, 4}; 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
[edit] 参阅
查找具有特定键的元素 (公共成员函数) | |
返回匹配特定键的元素数量 (公共成员函数) | |
返回与特定键匹配的元素范围 (公共成员函数) |