Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 646
pighead10 Avatar asked May 03 '11 16:05

pighead10


1 Answers

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.

like image 53
Nawaz Avatar answered Oct 20 '22 02:10

Nawaz