std::flat_map<Key,T,Compare,KeyContainer,MappedContainer>::find
来自cppreference.com
<tbody>
</tbody>
iterator find( const Key& key ); |
(1) | (C++23 起) |
const_iterator find( const Key& key ) const; |
(2) | (C++23 起) |
template< class K > iterator find( const K& x ); |
(3) | (C++23 起) |
template< class K > const_iterator find( const K& x ) const; |
(4) | (C++23 起) |
1,2) 寻找键等价于
key 的的元素。 3,4) 寻找键比较等价于值
x 的元素。此重载只有在限定标识 Compare::is_transparent 合法并指代类型时才会参与重载决议。它允许调用此函数时无需构造 Key 的实例。参数
| key | - | 要搜索的元素键值 |
| x | - | 能透明地与键比较的任何类型值 |
返回值
指向所需元素的迭代器。若找不到这种元素,则返回尾后(见 end())迭代器。
复杂度
与容器大小成对数。
示例
运行此代码
#include <iostream>
#include <flat_map>
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::flat_map<int, char> example{{1, 'a'}, {2, 'b'}};
if (auto search = example.find(2); search != example.end())
std::cout << "找到了 " << search->first << ' ' << search->second << '\n';
else
std::cout << "未找到\n";
// 透明比较演示。
std::flat_map<FatKey, char, std::less<>> example2{{{1, {}}, 'a'}, {{2, {}}, 'b'}};
LightKey lk = {2};
if (auto search = example2.find(lk); search != example2.end())
std::cout << "找到了 " << search->first.x << ' ' << search->second << '\n';
else
std::cout << "未找到\n";
// 获取常量迭代器。
// 编译器通过访问映射的方式来确定返回的是否是 const 类型的迭代器;
// 避免发生意外修改的一种最简单的方式是通过常量引用访问映射。
const auto& example2ref = example2;
if (auto search = example2ref.find(lk); search != example2.end())
{
std::cout << "找到了 " << search->first.x << ' ' << search->second << '\n';
// search->second = 'c'; // 错误:在只读对象中对成员
// 'std::pair<const FatKey, char>::second' 进行赋值
}
}
输出:
找到了 2 b
找到了 2 b
找到了 2 b
参阅
| 带越界检查访问指定的元素 (公开成员函数) | |
| 访问或插入指定的元素 (公开成员函数) | |
| 返回匹配特定键的元素数量 (公开成员函数) | |
| 返回匹配特定键的元素范围 (公开成员函数) |