std::map at() 方法
- C++98 起
// Non const version
T& at( const Key& key );
// Const version
const T& at( const Key& key ) const;
返回对指定索引pos
处元素的引用。
std::out_of_range
异常。
参数
key
- 要查找的元素的键
返回值
所请求元素的映射值的引用。
异常
如果容器不包含指定的键,则抛出 std::out_of_range
。
复杂度
对容器大小呈对数关系 - O(log size())。
示例
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";
}
可能输出
player1 zdobył 50 punktów.
terminate called after throwing an instance of 'std::out_of_range'
what(): map::at