Search code examples
c++dictionaryrangeerase

If first and last in a map erase range are equal will the element be removed or not?


According to this:

Iterators specifying a range within the map container to be removed: [first,last). i.e., the range includes all the elements between first and last, including the element pointed by first but not the one pointed by last.

This is ambiguous since it does not address the case where first and last are equal. If first and last are equal will the element be removed or not? This is a representation of the code in question:

map<uint16_t, boost::shared_ptr<SPacket> >::iterator it = m_MyMap.find(ack);
if (it != m_MyMap.end()) m_MyMap.erase(m_MyMap.begin(), it);

Solution

  • If first and last are equal will the element be removed or not?

    When first and last are equal that represent empty range and no elements will be erased. It is stated for std::vector::erase() documentation:

    The iterator first does not need to be dereferenceable if first==last: erasing an empty range is a no-op.

    semantics for std::map::erase() should be the same.

    map<uint16_t, boost::shared_ptr<SPacket> >::iterator it = m_MyMap.find(ack);
    if (it != m_MyMap.end()) m_MyMap.erase(m_MyMap.begin(), it);
    

    Code means - erase everything from begining to it but excluding it. if it equals to m_MyMap.begin() nothing will be erased.

    If you want to include element with key equal to ack you need to advance it:

    map<uint16_t, boost::shared_ptr<SPacket> >::iterator it = m_MyMap.find(ack);
    if (it != m_MyMap.end()) m_MyMap.erase(m_MyMap.begin(), std::next(it));