std::map<Key,T,Compare,Allocator>::at
來自 cppreference.com
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) 必須是良好形式且具有明確定義的行為,否則行為未定義。
僅當限定 ID Compare::is_transparent 有效並表示一個型別時,這些過載才參與過載決議。它允許在不構造
Key
例項的情況下呼叫此函式。目錄 |
[edit] 引數
key | - | 要查詢的元素的鍵 |
x | - | 可與鍵透明比較的任何型別的值 |
[edit] 返回值
對所請求元素的對映值的引用。
[edit] 異常
[edit] 複雜度
容器大小的對數級別。
注意
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__cpp_lib_associative_heterogeneous_insertion |
202311L |
(C++26) | 有序和無序關聯容器中剩餘成員函式的異構過載。(3,4) |
[edit] 示例
執行此程式碼
#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++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 464 | C++98 | map 沒有此成員函式 |
已新增 |
LWG 703 | C++98 | 缺少複雜度要求 | 已新增 |
LWG 2007 | C++98 | 返回值指的是所請求的元素 | 指其對映值 |
[edit] 參閱
訪問或插入指定元素 (public member function) | |
查詢具有特定鍵的元素 (public member function) |