0

I thought the only difference between std::unordered_map::operator[] and std::unordered_map::at is that std::unordered_map::at throws std::out_of_range if the key doesn't exist.

However, in the following code snippet, std::unordered_map::at works but std::unordered_map::operator[] gives a compiler error

const unordered_map<char, string> digit2Letters {
    {'2', "abc"},
    {'3', "def"},
    {'4', "ghi"},
};

digit2Letters.at('1') // works good
digit2Letters['1']; // compiler error: no operator "[]" matches these operands

Does anyone know why std::unordered_map::at works but std::unordered_map::operator[] fails?

iluvmath
  • 177
  • 4
  • 1
    `operator[]` is a non-const member function. Your `map` is `const`. I'm sure there's a dupe for this. – G.M. May 03 '22 at 19:42
  • 1
    `operator[]` doesn't work on const objects. – NathanOliver May 03 '22 at 19:42
  • Ohh yea. I found a dup here https://stackoverflow.com/questions/13354394/reading-object-from-const-unordered-map. operator[] is non-const as it adds a default value when the key doesn't exist. Makes sense. Thanks! – iluvmath May 03 '22 at 19:45

0 Answers0