命名空间
变体
操作

std::flat_map<Key,T,Compare,KeyContainer,MappedContainer>::at

来自 cppreference.cn
< cpp‎ | 容器‎ | flat map
 
 
 
 
T& at( const Key& key );
(1) (C++23 起)
const T& at( const Key& key ) const;
(2) (C++23 起)
template< class K >
T& at( const K& x );
(3) (C++23 起)
template< class K >
const T& at( const K& x ) const;
(4) (C++23 起)

返回具有指定键的元素的映射值的引用。如果不存在此类元素,则抛出 std::out_of_range 类型的异常。

1,2) 键等价于 key
3,4) 键与值 x 比较等价。映射值的引用通过表达式 this->find(x)->second 获取。
表达式 this->find(x) 必须格式良好且行为良好,否则行为未定义。
这些重载仅在限定 ID Compare::is_transparent 有效且表示一个类型时才参与重载决议。它允许在不构造 Key 实例的情况下调用此函数。

目录

[edit] 参数

key - 要查找的元素的键
x - 可与键透明比较的任何类型的值

[edit] 返回值

对所请求元素的映射值的引用。

[edit] 异常

1,2) 如果容器中不存在具有指定 key 的元素,则抛出 std::out_of_range
3,4) 如果容器中不存在指定元素,即如果 find(x) == end()true,则抛出 std::out_of_range

[edit] 复杂度

容器大小的对数级别。

[edit] 示例

#include <cassert>
#include <iostream>
#include <flat_map>
 
struct LightKey { int o; };
struct HeavyKey { int o[1000]; };
 
// The container must use std::less<> (or other transparent Comparator) to
// access overloads (3,4). This includes standard overloads, such as
// comparison between std::string and std::string_view.
bool operator<(const HeavyKey& x, const LightKey& y) { return x.o[0] < y.o; }
bool operator<(const LightKey& x, const HeavyKey& y) { return x.o < y.o[0]; }
bool operator<(const HeavyKey& x, const HeavyKey& y) { return x.o[0] < y.o[0]; }
 
int main()
{
    std::flat_map<int, char> map{{1, 'a'}, {2, 'b'}};
    assert(map.at(1) == 'a');
    assert(map.at(2) == 'b');
    try
    {
        map.at(13);
    }
    catch(const std::out_of_range& ex)
    {
        std::cout << "1) out_of_range::what(): " << ex.what() << '\n';
    }
 
#ifdef __cpp_lib_associative_heterogeneous_insertion
    // Transparent comparison demo.
    std::flat_map<HeavyKey, char, std::less<>> map2{{{1}, 'a'}, {{2}, 'b'}};
    assert(map2.at(LightKey{1}) == 'a');
    assert(map2.at(LightKey{2}) == 'b');
    try
    {
        map2.at(LightKey{13});
    }
    catch(const std::out_of_range& ex)
    {
        std::cout << "2) out_of_range::what(): " << ex.what() << '\n';
    }
#endif
}

可能的输出

1) out_of_range::what(): map::at:  key not found
2) out_of_range::what(): map::at:  key not found

[edit] 参阅

访问或插入指定元素
(public member function) [编辑]
查找具有特定键的元素
(public member function) [编辑]