std::map<Key,T,Compare,Allocator>::at
From 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) は、well-formed であり、well-defined な動作を持つ必要があります。そうでない場合、動作は未定義です。
これらのオーバーロードは、修飾ID Compare::is_transparent が有効で、型を指している場合にのみオーバーロード解決に参加します。これにより、
Key のインスタンスを構築せずにこの関数を呼び出すことができます。目次 |
[編集] パラメータ
| key | - | 検索する要素のキー |
| x | - | キーと透過的に比較できる任意の型の値 |
[編集] 戻り値
要求された要素のマップ値への参照。
[編集] 例外
[編集] 計算量
コンテナのサイズに対して対数時間。
注釈
| 機能テストマクロ | 値 | 規格 | 機能 |
|---|---|---|---|
__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 | 戻り値は要求された要素を参照していました。 | 対応する値を参照します。 |
[編集] 関連項目
| 指定された要素にアクセスまたは挿入する (public メンバ関数) | |
| 特定のキーを持つ要素を検索する (公開メンバ関数) |