I was under the impression one cant use erase
on a const iterator
. Check this code.
Why does the below code compile (C++11, gcc)?
long getMax(const bool get_new)
{
long max_val=0;
TO now=getNow();
map<TO, long>& m=get_new?m_new:m_old;
for(auto it=m.cbegin(); it !=m.cend())
{
if(now.compareTime((*it).first)<lookback)
{
max_val=max(max_val,
(*it).second);
++it;
}
else
{
it=m.erase(it);
}
}
return max_val;
}
The map itself is not constant, but my understanding is that the const iterator
should make this fail.
However, as it is perfectly legal to 'delete' a const pointer in C++ (try it, it works!), it should be (and the behavior has been corrected in C++11) legal as well to 'erase" a const iterator from a container, provided the container itself is not const.
No it doesn't free the memory if it is a naked pointer. You need to ensure that the memory is deallocated appropriately.
map erase() function in C++ STL Parameters: The function accepts one mandatory parameter key which specifies the key to be erased in the map container. Return Value: The function returns 1 if the key element is found in the map else returns 0.
The behavior has changed from C++11; std::map::erase takes const_iterator
as its parameter.
void erase( iterator pos ); // (until C++11)
iterator erase( const_iterator pos ); // (since C++11)
iterator erase( iterator pos ); // (since C++17)
For std::map::erase
, the passed iterator is just used as the position where the element would be deleted, not for modifying the element through it. That means const_iterator
would be fine. Before C++11, the support for const_iterator
was not very good, but the situation has changed from C++11. You should use const_iterator
instead of iterator
when possible now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With