std::map<Key,T,Compare,Allocator>::at

Returns a reference to the mapped value of the element with specified key. If no such element exists, an exception of type std::out_of_range is thrown.

# Declarations

T& at( const Key& key );
const T& at( const Key& key ) const;
template< class K >
T& at( const K& x );

(since C++26)

template< class K >
const T& at( const K& x ) const;

(since C++26)

# Parameters

# Return value

A reference to the mapped value of the requested element.

# Notes

Feature-test macro Value Std Feature __cpp_lib_associative_heterogeneous_insertion 202311L (C++26) Heterogeneous overloads for the remaining member functions in ordered and unordered associative containers. (3,4)

# Example

#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
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 464C++98map did not have this member functionadded
LWG 703C++98the complexity requirement was missingadded
LWG 2007C++98the return value referred to the requested elementrefers to its mapped value

# See also