Namespaces
Variants

std::flat_map<Key,T,Compare,KeyContainer,MappedContainer>:: at

From cppreference.net

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

指定されたキーを持つ要素のマップされた値への参照を返します。そのような要素が存在しない場合、 std::out_of_range 型の例外がスローされます。

1,2) キーは key と等価です。
3,4) キーが値 x 等価 と比較される。マップされた値への参照は、式 this - > find ( x ) - > second によって得られるかのように取得される。
this - > find ( x ) は適切に形成され、明確に定義された振る舞いを持たなければならず、そうでない場合の動作は未定義です。
これらのオーバーロードは、 Compare transparent である場合にのみ、オーバーロード解決に参加します。これにより、 Key のインスタンスを構築せずにこの関数を呼び出すことが可能になります。

目次

パラメータ

key - 検索する要素のキー
x - キーと透過的に比較可能な任意の型の値

戻り値

要求された要素のマップされた値への参照。

例外

1,2) std::out_of_range 指定された key を持つ要素がコンテナに存在しない場合に送出されます。
3,4) std::out_of_range 指定された要素がコンテナに存在しない場合、すなわち find ( x ) == end ( ) true の場合。

計算量

コンテナのサイズに対して対数的。

#include <cassert>
#include <iostream>
#include <flat_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::flat_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::flat_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

関連項目

指定された要素にアクセスまたは挿入
(公開メンバ関数)
特定のキーを持つ要素を検索
(公開メンバ関数)