Search code examples
c++stringerase

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.

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.

    In your case, count is 0, so you are removing 0 characters.