0

I have the following program. What I would like to accomplish is to create a constant reference to a mutable wrapper over unordered_map that I can pass around for read-only lookup. However, I am not able to compile the following code, due to the operator[] overloads.

From this code, does anyone know what I am doing wrong?

#include <unordered_map>
#include <string>

using std::unordered_map;
using std::string;

class M {
private:
    unordered_map<string, string> m;

public:
    string const& operator[](string const& s) const {
        return m[s]; // line 13
    }

    string& operator[](string const& s) {
        return m[s];
    }
};

int main() {
    M m;

    m[string("a")] = string("answer_a");

    M const& m1 = m;
    string const& test = m1[string("a")];

    return 0;
}

The error (on line 13) is

error: passing 'const std::unordered_map, std::basic_string >' as 'this' argument of 'std::__detail::_Map_base<_Key, _Pair, std::_Select1st<_Pair>, true, _Hashtable>::mapped_type& std::__detail::_Map_base<_Key, _Pair, std::_Select1st<_Pair>, true, _Hashtable>::operator[](const _Key&) [with _Key = std::basic_string, _Pair = std::pair, std::basic_string >, _Hashtable = std::_Hashtable, std::pair, std::basic_string >, std::allocator, std::basic_string > >, std::_Select1st, std::basic_string > >, std::equal_to >, std::hash >, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, std::__detail::_Prime_rehash_policy, false, false, true>, std::__detail::_Map_base<_Key, _Pair, std::_Select1st<_Pair>, true, _Hashtable>::mapped_type = std::basic_string]' discards qualifiers [-fpermissive]

David
  • 2,080
  • 5
  • 29
  • 44
  • 3
    What you're doing wrong is failing to read the documentation to find out what `operator[]` does for maps. – Lightness Races in Orbit Apr 09 '15 at 23:21
  • I wouldn't downvote the question though, it is a fair question and I'm pretty sure all of us made such mistakes before. Especially when http://stackoverflow.com/q/1642028/3093378 is the 3-rd most voted question on SO. – vsoftco Apr 09 '15 at 23:25

1 Answers1

6

The unordered_map operator[] is non-const, because it adds a map key when it does not exist yet. Instead, you should use

return m.at(s);
Bas in het Veld
  • 1,271
  • 10
  • 17