std::multimap<Key,T,Compare,Allocator>::find

来自cppreference.com
< cpp‎ | container‎ | multimap

iterator find( const Key& key );
(1)
const_iterator find( const Key& key ) const;
(2)
template< class K > iterator find( const K& x );
(3) (C++14 起)
template< class K > const_iterator find( const K& x ) const;
(4) (C++14 起)
1,2) 寻找键等于 key 的的元素。若容器中有数个拥有键 key 的元素,则可能返回任意一者。
3,4) 寻找键比较等价于值 x 的元素。此重载仅若有限定标识 Compare::is_transparent 合法并指代类型才参与重载决议。它允许无需构造 Key 的实例就调用此函数。

参数

key - 要搜索的元素键值
x - 能通透地与键比较的任何类型值

返回值

指向键等于 key 的元素的迭代器。若找不到这种元素,则返回尾后(见 end() )迭代器。

复杂度

与容器大小成对数。

示例

#include <iostream>
#include <map>
 
struct FatKey   { int x; int data[1000]; };
struct LightKey { int x; };
// 注:如上详述,容器必须使用 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::multimap<int,char> example = {{1,'a'},{2,'b'}};
 
    auto search = example.find(2);
    if (search != example.end()) {
        std::cout << "Found " << search->first << " " << search->second << '\n';
    } else {
        std::cout << "Not found\n";
    }
 
// 通透比较演示
    std::multimap<FatKey, char, std::less<>> example2 = { { {1, {} },'a'}, { {2, {} },'b'} };
 
    LightKey lk = {2};
    auto search2 = example2.find(lk);
    if (search2 != example2.end()) {
        std::cout << "Found " << search2->first.x << " " << search2->second << '\n';
    } else {
        std::cout << "Not found\n";
    }
// 获得 const 迭代器。
// 编译器通过访问 map 的路径决定是否返回(非) const 类型的迭代器;
// 为避免此目的所致的修改,最简单的选择之一是以 const 引用访问 map 。
    const auto& example2ref = example2;
    auto search3 = example2ref.find(lk);
    if (search3 != example2.end()) {
        std::cout << "Found " << search3->first.x << ' ' << search3->second << '\n';
    //  search3->second = 'c'; // 错误:在只读对象中赋值成员
                               // 'std::pair<const FatKey, char>::second'
    }
}

输出:

Found 2 b
Found 2 b
Found 2 b

参阅

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