我通常喜欢用 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
不需要在向其推送内容之前初始化向量?
https://en.cppreference.com/w/cpp/container/unordered_map/operator_at
插入就地构造的std::unordered_map<...>::operator[]
对象...如果value_type
不存在。这个函数等同于key
。 (C++17 起)return this->try_emplace(key).first->second;
请注意,地图还提供一个
at
成员进行边界检查。
https://en.cppreference.com/w/cpp/container/unordered_map/at
返回对键等于std::unordered_map<...>::at
的元素的映射值的引用。如果不存在这样的元素,则抛出key
类型的异常。std::out_of_range