为什么运算符[]是为conststd::vector定义的,而不是为conststd::map定义的



拥有以下代码:

#include <map>
#include <string>
#include <vector>
void foo1(const std::map<std::string, int> &m)
{
m["abcd"];
}
void foo2(const std::vector<std::vector<int>> &v)
{
v[0];
}

仅给出foo1的错误,而不给出foo2的错误。正如我所理解的map->它有两个数组,一个用于键,另一个用于值。我知道const map给了我const int这个值。但vector<vector<int>>也应该如此,因为经由[]访问元素也是const vector<int>,但被允许。此外,通过[]访问一个值并不意味着我想要write一个数据。我可以读取该值,那么为什么即使是const map也没有operator[]呢?(当编译器不知道我是要写还是要读时(。

编辑

问题在于语言设计,而非标准报价。正如在评论中一样->您需要1个运算符来写入映射operator[]。但矢量写入operator[]operator=需要2个运算符。为什么map::operator[]自动期望我要写?(因此,通过提供的密钥创建新的元素(?我可以像在矢量中一样,只是试图从地图中读取,如果密钥(对(不存在,它可以给出错误或警告,但没有必要立即创建它

这是因为如果引用的元素不存在,std::map::operator[]会插入到映射中。因此,该方法不能声明为const,因此不能在const对象上调用。

最新更新