Reputation: 7491
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
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
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