std::map at() method
- since C++98
// Non const version
T& at( const Key& key );
// Const version
const T& at( const Key& key ) const;
Returns a reference
to the mapped value of the element with key equivalent to key. If no such element exists, an exception ofstd::out_of_range
is thrown.
Parameters
key
- the key of the element to find
Return value
Reference to the mapped value of the requested element.
Exceptions
Throws std::out_of_range
if the container doesn't have the key specified.
Complexity
Logarithmic in the size of the container - O(log size()).
Example
Main.cpp
#include <iostream>
#include <map>
auto main() -> int {
std::map<std::string, int> playersScores = {
{ "player1", 50 },
{ "super_coder", 100 },
{ "andrew111", 41 }
};
std::cout << "player1 gained " << playersScores.at("player1") << " points.\n";
// Ooops! Incorrect key!
std::cout << "super_cader gained " << playersScores.at("super_cader") << " points.\n";
}
Possible output
player1 zdobył 50 punktów.
terminate called after throwing an instance of 'std::out_of_range'
what(): map::at
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.
Hover to see the original license.