0

I am inserting elements in a map avoiding duplicates, so I've written this code

std::unordered_map<size_t, size_t> idToPos;
for (it : list) {
    auto itPos = idToPos.find(it.id());
    if (itPos==idToPos.end()) {
        idToPos[itPos->first] = idToPos.size();
        do_something_else();
    }
}

The question is, if itPos==idToPos.end() is true, will itPos->second yield the same result as idToPos[itPos->first] given idToPos is an unordered_map?

Maxence1402
  • 107
  • 10

1 Answers1

1

When itPos==idToPos.end(), itPos->first is undefined, which leads to Undefined Behaviour.

You want

std::unordered_map<size_t, size_t> idToPos;
for (it : list) {
    auto itPos = idToPos.find(it.id());
    if (itPos==idToPos.end()) idToPos[it.id()] = idToPos.size();
}
YSC
  • 38,212
  • 9
  • 96
  • 149
  • What does UB mean? – Maxence1402 Apr 16 '21 at 09:23
  • My bad, UB means Undefined Behaviour. Let me update the answer. – YSC Apr 16 '21 at 09:25
  • Is there any way to avoid getting the id twice? Depending on the element it can be costly. I guess I can still use a new variable – Maxence1402 Apr 16 '21 at 09:28
  • `.emplace()` will handle duplicates, there is no need to use `.find` (searching the map twice, first time in `find`, second time in `[]`). – Evg Apr 16 '21 at 09:33
  • @Evg I did not specify though that I want to do something else if and only if the key isn't present. I read that ```emplace``` will return a pair whose second element is a boolean telling if the key is absent, is that it? – Maxence1402 Apr 16 '21 at 09:45
  • @Maxence1402, that's true. – Evg Apr 16 '21 at 10:36