STL Containers begin() / end() returns const_iterator ?
03 May, 2013 - 2 min read
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:
Compiler Error:
"No conversion from 'std::Tree_const_iterator<...> to std::Tree_iterator<...> exists'".
Answer:
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
isconst
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. Ex:
std::map::begin
iterator begin(); const_iterator begin() const;
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 tomymap.begin()
will pichup the overload that returns a const_iterator
instead of the overload that returns an iterator
.
End