以不同的方式填充地图

Populating map in a different way

这是填充地图的现有代码。

typedef unordered_map<std::string, SomeSet> StringToSetMap;

StringToSetMap myMap;

std::string str ("hello");

SomeSet &mySet = myMap[str]; //Map populates here

"SomeSet" 是类型定义 unordered_set.

据我所知,地图只能以上述方式填充here

这是如何以这种方式填充地图的?

See the docs 对于有问题的下标运算符。注意运算符的描述是它...

Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist

另请注意:

Return value

Reference to the mapped value of the new element if no element with key key existed. Otherwise a reference to the mapped value of the existing element whose key is equivalent to key.

"hello" 不是您地图中的键,因此它被插入并返回给您一个闪亮的新 SomeSet 对象的引用。

(注意:键要么是移动构造的,要么是复制构造的,但无论哪种方式,值始终是默认构造的。确保您有 SomeSet 的默认构造函数!)