2

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();
K. Shores
  • 875
  • 1
  • 18
  • 46

2 Answers2

5

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();
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
2

You should use const_iterator instead:

std::map<char, int>::const_iterator it = m.begin();
Slava
  • 43,454
  • 1
  • 47
  • 90
  • Ah, thank you. So, if I were allowed to use a regular iterator would the regular iterator be allowed to edit the map whereas the const_iterator knows it's not allowed to edit the map? – K. Shores Jan 15 '16 at 17:26
  • @K.Shores [Relevant](http://stackoverflow.com/questions/4527686/how-to-update-stdmap-after-using-the-find-method) – erip Jan 15 '16 at 17:26
  • 1
    @K.Shores yes that exact reason why there is regular `iterator` and `const_iterator` for `std::map` – Slava Jan 15 '16 at 17:34