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; } 
1
  • 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. Commented Apr 23, 2023 at 22:36

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.