pighead10
pighead10

Reputation: 4305

Constant map iterator won't set to mymap.begin()

map<string,Shopable*>::iterator it = mymap.begin();

The iterator appears to be constant, but items.begin() doesn't return a constant iterator. Or, that's what I think because the mouseover error is something like:

"No conversion from 'std::Tree_const_iterator<...> to std::Tree_iterator<...> exists'".

Why?

Upvotes: 11

Views: 14207

Answers (2)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361462

Use const_iterator as :

map<string,Shopable*>::const_iterator it = mymap.begin();

From the error, its clear that mymap.begin() returns const_iterator. That is because mymap is const in the function where you've written this, something like following:

void f(const std::map<int,int> & m)
{    //^^^^^ note this

      std::map<int,int>::const_iterator it = m.begin(); //m is const in f()
                       //^^^^^ note this
}

void g(std::map<int,int> & m)
{
      std::map<int,int>::iterator it = m.begin(); //m is non-const in g()
}

That is, const container (whether its std::map, std::vector etc) returns const_iterator and non-const container returns iterator.

Every container has overloaded functions of begin() and end(). So const container invokes the overloaded begin() which returns const_iterator and non-const container invokes the other overloaded begin() which returns iterator. And same for end() overloaded functions.

Upvotes: 25

The problem is that mymap in the code above is a constant map, not a mutable map (maybe it is a member of a class and that code is inside constant member function?). Thus the call to mymap.begin() will pichup the overload that returns a const_iterator instead of the overload that returns an iterator.

If you do not need to change the container through the iterator, use const_iterator. If you intend on modifying the map, make sure that you are using a non-const object for the loop (maybe the member function (if that is the case) should not be const?)

Upvotes: 4

Related Questions