你说得对operator[]
需要值类型是可默认构造的。
insert https://en.cppreference.com/w/cpp/container/unordered_map/insert才不是:
std::unordered_map<int, MyClass> my_map;
// Populate the map here
// Get element with key "1", creating a new one
// from the given value if it doesn't already exist
auto result = my_map.insert({1, <your value here>});
这为您提供了一个对,其中包含元素的迭代器(无论是新创建的还是已经存在的)和布尔值(告诉您是哪种情况)。
So:
auto& my_class = *result.first;
const bool was_inserted = result.second;
现在您可以利用这些信息做任何您想做的事情。很多时候你甚至不会关心result.second
并且可以忽略它。
对于更复杂的值类型,您可以使用emplace
,就像insert
但是,嗯,更好。假设您确实不希望在不使用该值的情况下构造该值,并且您有 C++17:
auto result = my_map.try_emplace(1, <your value's ctor args here here>);
如果你不在乎(或者没有 C++17):
auto result = my_map.emplace(1, <your value>);
这还是比insert
因为它可以将值移动到映射中,而不是复制它。
最终,如果你甚至不想产生不必要的 ctor args,你总是可以做一个find
首先,但最好尽量避免这种情况,因为插入操作本身也会进行查找。