Namespaces
Variants

std::multiset<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 等价的元素。
此重载仅当 Compare 满足 透明性 时参与重载决议。它允许在不构造 Key 实例的情况下调用此函数。

目录

参数

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::multiset<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::multiset<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

参见

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