Namespaces
Variants

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

From cppreference.net

T & at ( const Key & key ) ;
(1)
const T & at ( const Key & key ) const ;
(2)
template < class K >
T & at ( const K & x ) ;
(3) (C++26 起)
template < class K >
const T & at ( const K & x ) const ;
(4) (C++26 起)

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

1,2) 该键等同于 key
3,4) 该键与值 x 比较为 等价 。映射值的引用通过表达式 this - > find ( x ) - > second 获取。
表达式 this - > find ( x ) 必须格式正确且具有明确定义的行为,否则该行为是未定义的。
这些重载仅在 Compare 满足 透明性 时参与重载决议。这允许在不构造 Key 实例的情况下调用此函数。

目录

参数

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

返回值

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

异常

1,2) std::out_of_range 若容器中不存在带有指定 key 的元素。
3,4) std::out_of_range 若容器中不存在指定元素,即当 find ( x ) == end ( ) true 时。

复杂度

与容器大小呈对数关系。

注释

功能测试 标准 功能特性
__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]; };
// 容器必须使用 std::less<>(或其他透明比较器)来
// 访问重载版本(3,4)。这包括标准重载,例如
// std::string 与 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
    // 透明比较演示。
    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++标准。

缺陷报告 适用标准 发布时行为 正确行为
LWG 464 C++98 map 没有此成员函数 已添加
LWG 703 C++98 缺少复杂度要求 已添加
LWG 2007 C++98 返回值指向请求的元素 指向其映射值

参见

访问或插入指定元素
(公开成员函数)
查找具有特定键的元素
(公开成员函数)