std::set find() 方法
- 自 C++14 起
- 直到 C++14
// (1) Const version
size_type count( const Key& key ) const;
// (2) Const version
template< class K >
size_type count( const K& x ) const;
// (1) Const version
size_type count( const Key& key ) const;
- (1-2) 查找键等同于
key
的元素。 - (3-4) 查找键与值
x
比较等同的元素。此重载仅当限定符Compare::is_transparent
有效并表示一种类型时才参与重载解析。它允许在不构造Key
实例的情况下调用此函数。
参数
key
- 要计数的元素的键值x
- 可以与键透明比较的任何类型的值
返回值
指向键等同于 key
的元素的迭代器。如果找不到此类元素,则返回 past-the-end(参见end()
)迭代器。
复杂度
对容器大小呈对数关系 - O(log size())。
异常
(无)
备注
特性测试宏:__cpp_lib_generic_unordered_lookup
(用于重载 (3-4))。
示例
Main.cpp
#include <iostream>
#include <set>
struct FatKey { int x; int data[1000]; };
struct LightKey { int x; };
// Note: as detailed above, the container must use std::less<> (or other
// transparent Comparator) to access these overloads.
// This includes standard overloads, such as between std::string and std::string_view.
bool operator<(const FatKey& fk, const LightKey& lk) { return fk.x < lk.x; }
bool operator<(const LightKey& lk, const FatKey& fk) { return lk.x < fk.x; }
bool operator<(const FatKey& fk1, const FatKey& fk2) { return fk1.x < fk2.x; }
int main()
{
// simple comparison demo
std::set<int> example = {1, 2, 3, 4};
auto search = example.find(2);
if (search != example.end()) {
std::cout << "Found " << (*search) << '\n';
} else {
std::cout << "Not found\n";
}
// transparent comparison demo
std::set<FatKey, std::less<>> example2 = { {1, {} }, {2, {} }, {3, {} }, {4, {} } };
LightKey lk = {2};
auto search2 = example2.find(lk);
if (search2 != example2.end()) {
std::cout << "Found " << search2->x << '\n';
} else {
std::cout << "Not found\n";
}
}
可能输出
Found 2
Found 2