Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No viable overloaded operator[] for type

Tags:

c++

I have defined a type:

typedef unordered_map<string, list<string>> Graph;

I have a key:

string v = "A12";

When I try to access the list using the key:

for (auto w = g[v].begin(); w != g[v].end(); w++)
    {

        ...
    }

g is type Graph, I get the error:

No viable overloaded operator[] for type 'const Graph'

How can I fix this issue?

like image 557
Bob Avatar asked Dec 13 '16 20:12

Bob


1 Answers

The problem is that g is a const graph&. The indexing operator [] may need to create a new element for the map thus mutating it. That's why you cannot use it on a const graph& (the problem is const).

You can use g.at(key) instead that throws an exception if the key is not present.

like image 79
6502 Avatar answered Nov 04 '22 03:11

6502