std::set<Key,Compare,Allocator>:: find
From cppreference.net
|
iterator find
(
const
Key
&
key
)
;
|
(1) | (自 C++26 起为 constexpr) |
|
const_iterator find
(
const
Key
&
key
)
const
;
|
(2) | (自 C++26 起为 constexpr) |
|
template
<
class
K
>
iterator find ( const K & x ) ; |
(3) |
(自 C++14 起)
(自 C++26 起为 constexpr) |
|
template
<
class
K
>
const_iterator find ( const K & x ) const ; |
(4) |
(自 C++14 起)
(自 C++26 起为 constexpr) |
1,2)
查找键值等于
key
的元素。
3,4)
查找键值与
x
等价的元素。
目录 |
参数
| key | - | 要搜索元素的键值 |
| x | - | 可与键进行透明比较的任意类型值 |
返回值
指向所请求元素的迭代器。若找不到该元素,则返回尾后(参见 end() )迭代器。
复杂度
与容器大小呈对数关系。
注释
| 功能测试 宏 | 值 | 标准 | 功能 |
|---|---|---|---|
__cpp_lib_generic_associative_lookup
|
201304L
|
(C++14) | 关联容器 中的异构比较查找;重载版本 ( 3,4 ) |
示例
运行此代码
#include <iostream> #include <set> struct LightKey { int x; }; struct FatKey { int x; int data[1000]; // 一个沉重的数据块 }; // 如上所述,容器必须使用 std::less<>(或其他透明比较器)来访问这些重载。 // 这包括标准重载,例如 std::string 与 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() { // 简单比较演示。 std::set<int> example{1, 2, 3, 4}; if (auto search = example.find(2); search != example.end()) std::cout << "Found " << (*search) << '\n'; else std::cout << "Not found\n"; // 透明比较演示。 std::set<FatKey, std::less<>> example2{{1, {}}, {2, {}}, {3, {}}, {4, {}}}; LightKey lk = {2}; if (auto search = example2.find(lk); search != example2.end()) std::cout << "Found " << search->x << '\n'; else std::cout << "Not found\n"; }
输出:
Found 2 Found 2
参见
|
返回匹配特定键的元素数量
(公开成员函数) |
|
|
返回匹配特定键的元素范围
(公开成员函数) |