JASON
JASON

Reputation: 7491

map<int, vector<int> > graph and graph[i].begin() cannot be resolved

I had this problem where I had a map<int, vector<int> > graph and I tried to access graph[i].begin() where int i = 0;, and it cannot be resolved.

The error is:

error: no viable overloaded operator[] for type 'const map<int, vector<int> >

Could anyone explain this? Thanks!

Upvotes: 0

Views: 86

Answers (2)

Ulrich Eckhardt
Ulrich Eckhardt

Reputation: 17415

Note the "const" in the error message. Since operator[] on a map will create the element on demand, operator[] needs to have write access. In your case, it doesn't, so the non-const operator[] is not viable.

Upvotes: 1

Cornstalks
Cornstalks

Reputation: 38218

operator[] is not a const member, and so cannot be applied to a const map.

Why is operator[] nonconst? Because it will insert the element into the map if it doesn't exist (which would modify the map).

Upvotes: 4

Related Questions