🐛 avoid using an invalidated iterator

This commit is contained in:
Niels Lohmann 2021-11-09 14:52:16 +01:00
parent fbea78afca
commit d2ddce0a37
No known key found for this signature in database
GPG Key ID: 7F3CEA63AE251B69
2 changed files with 16 additions and 6 deletions

View File

@ -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

View File

@ -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