std::map operator[]
- 自 C++11 起
- C++98 起
// (1) Non const version only
T& operator[]( const Key& key );
// (2) Non const version only
T& operator[]( Key&& key );
// (1) Non const version only
T& operator[]( const Key& key );
返回对指定索引pos
处元素的引用。
- 自 C++11 起
- 直到 C++11
(1) 如果键不存在,则就地构造一个 value_type
对象,该对象由 std::piecewise_construct, std::forward_as_tuple(key), std::tuple<>()
构造。
自 C++17 起,此函数等效于 return this->try_emplace(key).first->second
。
当使用默认分配器时,这会导致键从 key 复制构造,并且映射值被值初始化。
类型要求
value_type
必须满足从std::piecewise_construct
、std::forward_as_tuple(key)
、std::tuple<>()
EmplaceConstructible 的要求。当使用默认分配器时,这意味着key_type
必须满足 CopyConstructible 的要求,并且mapped_type
必须满足 DefaultConstructible 的要求。
(2) 如果键不存在,则就地构造一个 value_type
对象,该对象由 std::piecewise_construct
、std::forward_as_tuple(std::move(key))
、std::tuple<>()
构造。
自 C++17 起,此函数等效于 return this->try_emplace(key).first->second
。
当使用默认分配器时,这会导致键从 key 移动构造,并且映射值被值初始化。
类型要求
value_type
必须满足从std::piecewise_construct
、std::forward_as_tuple(std::move(key))
、std::tuple<>()
EmplaceConstructible 的要求。当使用默认分配器时,这意味着key_type
必须满足 MoveConstructible 的要求,并且mapped_type
必须满足 DefaultConstructible 的要求。
(1) 如果键不存在,则插入 value_type(key, T())
。此函数等效于返回 insert(std::make_pair(key, T())).first->second
。如果执行插入,则映射值将进行值初始化(类类型默认构造,否则零初始化),并返回对其的引用。
类型要求
key_type
必须满足 CopyConstructible 的要求。mapped_type
必须满足 CopyConstructible 和 DefaultConstructible 的要求。
参数
key
- 要查找的元素的键
返回值
引用
如果不存在键为 key 的元素,则返回新元素的映射值的引用。否则返回引用到现有元素的映射值的引用,其键与 key 等效。异常
如果任何操作抛出异常,则插入无效。
复杂度
对容器大小呈对数。
示例
#include <iostream>
#include <map>
auto main() -> int {
std::map<std::string, int> playersScores = {
{ "player1", 50 },
{ "super_coder", 100 },
{ "andrew111", 41 }
};
std::cout << "player1 zdobył " << playersScores["player1"] << " punktów.\n";
std::cout << "super_cader zdobył " << playersScores["super_cader"] << " punktów.\n";
}
player1 zdobył 50 punktów.
super_cader zdobył 0 punktów.