So this is silly:
Nodes[pos] = node;
return &Nodes[pos];
because I insert and then do a lookup. I tried like this:
return &Nodes.emplace(pos, node).first->second;
but it doesn't return the reference.
CodePudding user response:
You can use insert
/emplace
like this:
int& f1(std::unordered_map<int, int>& m) {
auto [iterator, was_inserted] = m.insert({10, 100});
return iterator->second;
}
operator[]
can also create the key if it doesn't exist, so you can also do:
int& f2(std::unordered_map<int, int>& m) {
auto& node = m[10];
node = 100;
return node;
}