名前空間
変種
操作

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

From cppreference.com
 
 
 
 
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) は、well-formed であり、well-defined な動作を持つ必要があります。そうでない場合、動作は未定義です。
これらのオーバーロードは、修飾子付きID Compare::is_transparent が有効で、型を指す場合にのみオーバーロード解決に参加します。これにより、Key のインスタンスを構築せずにこの関数を呼び出すことができます。

目次

[編集] パラメータ

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

[編集] 戻り値

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

[編集] 例外

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

[編集] 計算量

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

[編集]

#include <cassert>
#include <iostream>
#include <flat_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::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
    // Transparent comparison demo.
    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

[編集] 関連項目

指定された要素にアクセスまたは挿入する
(public メンバ関数) [編集]
特定のキーを持つ要素を検索する
(公開メンバ関数) [編集]
English 日本語 中文(简体) 中文(繁體)