跳到主要内容

std::map at() 方法

// 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
本文档源自此 CppReference 页面。它可能经过了修改以进行改进或满足编辑偏好。点击“编辑此页面”以查看此文档的所有更改。
悬停查看原始许可证。

std::map at() 方法

// 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
本文档源自此 CppReference 页面。它可能经过了修改以进行改进或满足编辑偏好。点击“编辑此页面”以查看此文档的所有更改。
悬停查看原始许可证。