命名空间
变体
操作

std::map<Key,T,Compare,Allocator>::at

来自 cppreference.cn
< cpp‎ | container‎ | map
 
 
 
 
T& at( const Key& key );
(1)
const T& at( const Key& key ) const;
(2)
template< class K >
T& at( const K& x );
(3) (since C++26)
template< class K >
const T& at( const K& x ) const;
(4) (since C++26)

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

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

目录

[编辑] 参数

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

[编辑] 返回值

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

[编辑] 异常

1,2) std::out_of_range 如果容器没有具有指定 key 的元素。
3,4) std::out_of_range 如果容器没有指定的元素,即如果 find(x) == end()true

[编辑] 复杂度

容器大小的对数。

注解

特性测试 Std 特性
__cpp_lib_associative_heterogeneous_insertion 202311L (C++26) 用于 有序无序 关联 容器 中剩余成员函数的异构重载。 (3,4)

[编辑] 示例

#include <cassert>
#include <iostream>
#include <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::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::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

缺陷报告

以下行为更改的缺陷报告被追溯应用于先前发布的 C++ 标准。

DR 应用于 已发布行为 正确行为
LWG 464 C++98 map 没有此成员函数 已添加
LWG 703 C++98 缺少复杂度要求 已添加
LWG 2007 C++98 返回值引用请求的元素 引用其映射值

[编辑] 参见

访问或插入指定元素
(公共成员函数) [编辑]
查找具有特定键的元素
(公共成员函数) [编辑]