CppDS.com

C++ 98 11 14 17 20 手册

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 的元素。此重载仅若若有限定 id Compare::is_transparent 合法并且指代类型才参与重载决议。允许调用此函数而无需构造 Key 的实例。

参数

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

返回值

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

复杂度

与容器大小成对数。

示例

#include <iostream>
#include <map>
struct FatKey   { int x; int data[1000]; };
struct LightKey { int x; };
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";
    }
}

输出:

Found 2 b
Found 2 b

参阅

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