为什么具有向量值的 C++ unordered_maps 不需要向量初始化

问题描述 投票:0回答:1

我通常喜欢用 Python 编程,我注意到在一个用 C++ 编写的 Leetcode 问题解决方案中,

unordered_map<string, vector<string>>
不需要在将向量推送到之前对其进行初始化。

例如,类似下面的代码在C++中可以成功运行

unordered_map<string, vector<string>> example;

example["example_key"].push_back("example_elem");

但是在 Python 中,类似的代码会返回一个 KeyError,因为与键关联的列表还没有被初始化

example = {}

example["example_key"].append("example_elem")

为什么

unordered_map
不需要在向其推送内容之前初始化向量?

c++ vector unordered-map
1个回答
3
投票

https://en.cppreference.com/w/cpp/container/unordered_map/operator_at

std::unordered_map<...>::operator[]
插入就地构造的
value_type
对象...如果
key
不存在。这个函数等同于
return this->try_emplace(key).first->second;
。 (C++17 起)

请注意,地图还提供一个

at
成员进行边界检查。

https://en.cppreference.com/w/cpp/container/unordered_map/at

std::unordered_map<...>::at
返回对键等于
key
的元素的映射值的引用。如果不存在这样的元素,则抛出
std::out_of_range
类型的异常。

© www.soinside.com 2019 - 2024. All rights reserved.