【发布时间】:2022-01-21 16:57:59
【问题描述】:
#include <iostream>
#include <map>
int main(void) {
std::map<char, int> mapint;
mapint.insert({'a', 1});
mapint.insert({'b', 2});
// subscript operator is overloaded to return iterator.second (the value with key 'a')
int ex = mapint['a'];
std::cout << ex << std::endl;
// Why does this NOT traslate to 1=10 ?
// instead it replaces or creates pair <'a',10>...
mapint['a'] = 10;
for (auto i : mapint) {
std::cout << i.first << "," << i.second << std::endl;
}
// OUTPUT
// 1
// a,10
// b,2
return 0;
}
map 运算符是如何被重载的?我尝试查看地图的代码,但找不到任何可以回答我的问题的东西...
我想为我的一门课做类似的事情,我认为弄清楚这一点应该会有很大帮助!
【问题讨论】:
-
对不起,我还是没看到...
-
向下滚动到副本顶部答案中的“数组下标”
-
mapint['a']返回与键'a'对应的值的引用。如果没有这样的值,它会插入一个,默认初始化;然后返回对这个新插入的值的引用。