Reputation: 1005
So, I am trying to get an iterator to a map that I am passing in as a const reference to a function. My compiler complains when I do something like this:
bool func(string s, const map<char, int>& m){
std::map<char, int>::iterator it = m.begin();
/*more code here...*/
}
How should I do this?
The error message is:
error: no viable conversion from 'const_iterator' (aka '__map_const_iterator<typename __base::const_iterator>') to 'std::map<char, int>::iterator'
(aka '__map_iterator<typename __base::iterator>')
std::map<char, int>::iterator it = m.begin();
Upvotes: 2
Views: 2553
Reputation: 180500
The issue here is m
is const
so m.begin()
returns a const_iterator
not an iterator
. You either need to use:
std::map<char, int>::const_iterator it = m.begin();
Or for simplicity use auto
and you have:
auto it = m.begin();
Upvotes: 5
Reputation: 44238
You should use const_iterator
instead:
std::map<char, int>::const_iterator it = m.begin();
Upvotes: 2