std::map<Key,T,Compare,Allocator>::at
来自cppreference.com
<tbody>
</tbody>
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::is_transparent 合法并指代类型时才会参与重载决议。它允许调用此函数时无需构造 Key 的实例。参数
| key | - | 要找到的元素的键 |
| x | - | 可以透明地与键比较的任意类型的值 |
返回值
到所请求元素的被映射值的引用。
异常
1,2) 在容器没有指定
key 的元素时抛出 std::out_of_range。3,4) 在容器没有指定的元素,即当
find(x) == end() 为 true 时抛出 std::out_of_range。复杂度
与容器大小成对数。
注解
| 功能特性测试宏 | 值 | 标准 | 功能特性 |
|---|---|---|---|
__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 | 返回值指代请求元素 | 指代该元素的被映射值 |
参阅
| 访问或插入指定的元素 (公开成员函数) | |
| 寻找带有特定键的元素 (公开成员函数) |