🐛 avoid using an invalidated iterator
This commit is contained in:
parent
fbea78afca
commit
d2ddce0a37
@ -112,11 +112,14 @@ template <class Key, class T, class IgnoredLess = std::less<Key>,
|
||||
|
||||
iterator erase(iterator first, iterator last)
|
||||
{
|
||||
auto elements_affected = std::distance(first, last);
|
||||
const auto offset = std::distance(Container::begin(), first);
|
||||
const auto elements_affected = std::distance(first, last);
|
||||
|
||||
// This is the start situation. We need to delete elements_affected
|
||||
// elements (3 in this example: e, f, g), and need to return an
|
||||
// iterator past the last deleted element (h in this example).
|
||||
// Note that offset is the distance from the start of the vector
|
||||
// to first. We will need this later.
|
||||
|
||||
// [ a, b, c, d, e, f, g, h, i, j ]
|
||||
// ^ ^
|
||||
@ -149,8 +152,10 @@ template <class Key, class T, class IgnoredLess = std::less<Key>,
|
||||
// ^ ^
|
||||
// first last
|
||||
|
||||
// first is now pointing past the last deleted element
|
||||
return first;
|
||||
// first is now pointing past the last deleted element, but we cannot
|
||||
// use this iterator got invalidated by the resize call. Instead, we
|
||||
// can return begin() + offset.
|
||||
return Container::begin() + offset;
|
||||
}
|
||||
|
||||
size_type count(const Key& key) const
|
||||
|
||||
@ -17499,11 +17499,14 @@ template <class Key, class T, class IgnoredLess = std::less<Key>,
|
||||
|
||||
iterator erase(iterator first, iterator last)
|
||||
{
|
||||
auto elements_affected = std::distance(first, last);
|
||||
const auto offset = std::distance(Container::begin(), first);
|
||||
const auto elements_affected = std::distance(first, last);
|
||||
|
||||
// This is the start situation. We need to delete elements_affected
|
||||
// elements (3 in this example: e, f, g), and need to return an
|
||||
// iterator past the last deleted element (h in this example).
|
||||
// Note that offset is the distance from the start of the vector
|
||||
// to first. We will need this later.
|
||||
|
||||
// [ a, b, c, d, e, f, g, h, i, j ]
|
||||
// ^ ^
|
||||
@ -17536,8 +17539,10 @@ template <class Key, class T, class IgnoredLess = std::less<Key>,
|
||||
// ^ ^
|
||||
// first last
|
||||
|
||||
// first is now pointing past the last deleted element
|
||||
return first;
|
||||
// first is now pointing past the last deleted element, but we cannot
|
||||
// use this iterator got invalidated by the resize call. Instead, we
|
||||
// can return begin() + offset.
|
||||
return Container::begin() + offset;
|
||||
}
|
||||
|
||||
size_type count(const Key& key) const
|
||||
|
||||
Loading…
Reference in New Issue
Block a user