std::multimap find() 方法
- 自 C++14 起
- C++98 起
// (1) Non const version
iterator find( const Key& key );
// (2) Const version
const_iterator find( const Key& key ) const;
// (3) Non const version
template< class K >
iterator find( const K& x );
// (4) Const version
template< class K >
const_iterator find( const K& x ) const;
// (1) Non const version
iterator find( const Key& key );
// (2) Const version
const_iterator find( const Key& key ) const;
- (1-2) 查找键等同于
key
的元素。如果容器中有多个键相同的元素,则可能返回其中任何一个。 - (3-4) 查找键与值
x
比较等同的元素。此重载仅当限定 idCompare::is_transparent
有效并表示一种类型时才参与重载决议。它允许在不构造Key
实例的情况下调用此函数。
参数
key
- 要计数的元素的键值x
- 可以与键透明比较的任何类型的值
返回值
指向键等同于 key 的元素的迭代器。如果未找到此类元素,则返回末尾(参见 end()
)迭代器。
复杂度
对容器大小呈对数关系 - O(log size())。
异常
(无)
备注
特性测试宏:__cpp_lib_generic_associative_lookup
(用于重载 (3) 和 (4))。
示例
Main.cpp
#include <iostream>
#include <map>
struct FatKey { int x; int data[1000]; };
struct LightKey { int x; };
// Note: as detailed above, the container must use std::less<> (or other
// transparent Comparator) to access these overloads.
// This includes standard overloads, such as between std::string and 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()
{
// simple comparison demo
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";
}
// transparent comparison demo
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";
}
// Obtaining const iterators.
// Compiler decides whether to return iterator of (non) const type by way of accessing
// map; to prevent modification on purpose, one of easiest choices is to access map by
// const reference.
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'; // error: assignment of member
// 'std::pair<const FatKey, char>::second'
// in read-only object
}
}
输出
Found 2 b
Found 2 b
Found 2 b