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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With