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
が
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]; }; // コンテナはオーバーロード(3,4)にアクセスするために std::less<>(または他の透過的比較子)を使用する必要があります // これには、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++規格に対して遡及的に適用されました。
| DR | 適用対象 | 公開時の動作 | 正しい動作 |
|---|---|---|---|
| LWG 464 | C++98 |
map
はこのメンバ関数を持っていなかった
|
追加された |
| LWG 703 | C++98 | 計算量の要件が欠落していた | 追加された |
| LWG 2007 | C++98 | 戻り値が要求された要素を参照していた | そのマップされた値を参照する |
関連項目
|
指定された要素にアクセスまたは挿入
(公開メンバ関数) |
|
|
特定のキーを持つ要素を検索
(公開メンバ関数) |