Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why doesn't `str.erase(0, 0)` erase the first character of a string?

According to cplusplus,

first, last

Iterators specifying a range within the string] to be removed: [first,last). i.e., the range includes all the characters between first and last, including the character pointed by first but not the one pointed by last.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In which first, last are the parameters for the string::erase function. So str.erase(0, 0) should work. However, it doesn’t erase any character, and the string is left as normal. Which is strange, as the first character of a string is denoted by 0.

However, when trying str.erase(0, 1), the first character of the string is erased, which makes sense, as https://cplusplus.com words it as ‘Includes all the characters between first and last, including the character pointed by first but not the one pointed by last.’

I first thought of it being that not having the last character removed had priority over removing the first character, however this can’t be right, as running str.erase(1, 1) erases the second character of the string.

Why is this? Is this just an issue in the language itself?

>Solution :

str.erase(0,0) uses the version that takes an index and a count. From std::string::erase:

basic_string& erase( size_type index = 0, size_type count = npos );     (1) (constexpr since C++20)
  1. Removes std::min(count, size() - index) characters starting at index.

As you can see, the behavior is to remove std::min(count, size() - index) characters starting from first passed argument index.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading