1

Just asking why I'm not able to delete an interator as the beginning of the string to the end

I tried to do this:
The first called to the erase method work finely but not the second, why ?

int main()
{
    std :: string   str{"     Supprimer les espaces a la fin et au debut      "};
    
    std :: string :: const_iterator itStart{ std :: find_if_not(std :: cbegin(str), std :: cend(str), isspace) };
    std :: string :: const_reverse_iterator itEnd{ std :: find_if_not(std :: crbegin(str), std :: crend(str), isspace) };

    std :: cout << *itStart << std :: endl;
    std :: cout << *itEnd << std :: endl;
    str.erase(std :: cbegin(str), itStart);
    str.erase(itEnd, std :: end(str));
    std :: cout << str << "|" << std :: endl;
    return 0;
}
  • 3
    After the first call to the erase, the `itEnd` isn't pointing to the same character anymore ... Change the order, or move the definition of `itEnd` after the first call to erase. – ChrisMM Apr 23 '23 at 22:36

1 Answers1

3

erase() invalidates all iterators for any part of the sequence on or after the point of erasure.

itEnd was initialized before the first call to erase() and it references the part of the string after the erase()d range. As such the first erase() call invalidates it. It is no longer valid. Subsequent use of the iterator, in this manner, results in undefined behavior.

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148