Namespaces
Variants

std::flat_multimap<Key,T,Compare,KeyContainer,MappedContainer>:: find

From cppreference.net

iterator find ( const Key & key ) ;
(1) (自 C++23 起)
(自 C++26 起为 constexpr)
const_iterator find ( const Key & key ) const ;
(2) (自 C++23 起)
(自 C++26 起为 constexpr)
template < class K >
iterator find ( const K & x ) ;
(3) (自 C++23 起)
(自 C++26 起为 constexpr)
template < class K >
const_iterator find ( const K & x ) const ;
(4) (自 C++23 起)
(自 C++26 起为 constexpr)
1,2) 查找键值等于 key 的元素。若容器中存在多个具有相同键的元素,则可能返回其中任意一个。
3,4) 查找键值与 x 等价的元素。
此重载仅当 Compare 满足 透明性 时参与重载决议。它允许在不构造 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_multimap<int, char> example{{1, 'a'}, {2, 'b'}};
    if (auto search = example.find(2); search != example.end())
        std::cout << "Found " << search->first << ' ' << search->second << '\n';
    else
        std::cout << "Not found\n";
    // 透明比较演示。
    std::flat_multimap<FatKey, char, std::less<>> example2{{{1, {}}, 'a'}, {{2, {}}, 'b'}};
    LightKey lk = {2};
    if (auto search = example2.find(lk); search != example2.end())
        std::cout << "Found " << search->first.x << ' ' << search->second << '\n';
    else
        std::cout << "Not found\n";
    // 获取常量迭代器。
    // 编译器根据访问映射的方式决定返回(非)常量类型的迭代器;
    // 为防止有意修改,最简单的方法之一是通过常量引用访问映射。
    const auto& example2ref = example2;
    if (auto search = example2ref.find(lk); search != example2.end())
    {
        std::cout << "Found " << search->first.x << ' ' << search->second << '\n';
    //  search->second = 'c'; // 错误:对只读对象中的成员
                              // 'std::pair<const FatKey, char>::second' 进行赋值
    }
}

输出:

Found 2 b
Found 2 b
Found 2 b

参阅

返回匹配特定键的元素数量
(公开成员函数)
返回匹配特定键的元素范围
(公开成员函数)