名稱空間
變體
操作

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

來自 cppreference.com
< cpp‎ | 容器‎ | flat map
 
 
 
 
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) 必須格式良好且行為良好,否則行為未定義。
這些過載僅在限定 ID Compare::is_transparent 有效且表示一個型別時才參與過載決議。它允許在不構造 Key 例項的情況下呼叫此函式。

目錄

[edit] 引數

key - 要查詢的元素的鍵
x - 可與鍵透明比較的任何型別的值

[edit] 返回值

對所請求元素的對映值的引用。

[edit] 異常

1,2) 如果容器中不存在具有指定 key 的元素,則丟擲 std::out_of_range
3,4) 如果容器中不存在指定元素,即如果 find(x) == end()true,則丟擲 std::out_of_range

[edit] 複雜度

容器大小的對數級別。

[edit] 示例

#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

[edit] 參閱

訪問或插入指定元素
(public member function) [編輯]
查詢具有特定鍵的元素
(public member function) [編輯]