Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why const_iterator could be used with std::map::erase

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.

like image 712
chrise Avatar asked Dec 21 '16 05:12

chrise


People also ask

Can you erase a const iterator?

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.

Does map erase deallocate memory?

No it doesn't free the memory if it is a naked pointer. You need to ensure that the memory is deallocated appropriately.

What does map erase return?

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.


1 Answers

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.

like image 167
songyuanyao Avatar answered Sep 28 '22 03:09

songyuanyao