The erase() function in C++ strings removes characters from a std::string, and it has three overloads: erase by position and count, erase by iterator, and erase by iterator range. The simplest form is str.erase(pos, count), which deletes count characters starting at index pos and returns a reference to the modified string.
Why erase() Matters
Strings are mutable in C++, but you cannot directly assign a single character to null or use a simple assignment to delete a middle chunk. erase() is the standard, efficient way to remove characters without creating a new string object. It is part of the std::basic_string class template, so it works for std::string, std::wstring, and other character types. The function is defined in the <string> header, which you must include.
The Three Overloads Explained
All three overloads are member functions, meaning you call them on an existing string object. Here is each one with a concrete example.
1. Erase by Position and Count
Syntax: string& erase(size_type pos = 0, size_type count = npos);
This removes count characters starting at index pos. If you omit arguments, it erases everything from position 0 to the end (i.e., clears the string). If count is larger than the remaining length, it erases up to the end. It returns a reference to the string, so you can chain calls.
std::string s = "Hello, World!";
s.erase(5, 7); // removes ", World"
// s is now "Hello!"
2. Erase by Iterator
Syntax: iterator erase(const_iterator position);
This removes a single character at the position pointed to by the iterator. It returns an iterator to the character that followed the erased one (or end() if you erased the last character). This is useful when you are iterating and conditionally deleting.
std::string s = "abc";
auto it = s.begin() + 1; // points to 'b'
s.erase(it);
// s is now "ac"
3. Erase by Iterator Range
Syntax: iterator erase(const_iterator first, const_iterator last);
This removes all characters in the half-open range [first, last). It returns an iterator to the character that followed the last removed one. This is the most flexible for deleting a substring when you already have iterators.
std::string s = "abcdef";
s.erase(s.begin() + 1, s.begin() + 4); // removes "bcd"
// s is now "aef"
How to Choose the Right Overload
Your choice depends on what you have available:
- If you know the index and length, use the first overload. It is the most readable and does not require iterator arithmetic.
- If you are inside a loop that uses iterators (e.g., with
std::find), use the iterator overloads to avoid invalidating your position. - If you want to remove a range that you already have as iterators (e.g., from
std::findtostd::find), use the range version.
Remember that the first overload returns a reference, while the iterator overloads return an iterator. This difference matters if you want to chain or continue iterating.
Common Pitfalls and Misconceptions
A frequent mistake is assuming erase() works like pop_back() for the last character. pop_back() is a separate member function that removes exactly one character from the end. erase() can do that too, but pop_back() is clearer and slightly more efficient.
Another misconception: erase() does not reallocate the string’s capacity. It only shifts characters and updates the size. This means the capacity remains the same, which is good for performance but can surprise you if you expect memory to shrink. To release unused capacity, you can call shrink_to_fit() (C++11 onward).
Be careful with the default argument npos. If you call s.erase(5) without a second argument, it erases from index 5 to the end. That is correct, but if you accidentally pass a negative number (which converts to a huge unsigned value), you will erase everything from that position onward. Always use size_t or a non-negative integer.
Performance and Efficiency
Erasing characters from the middle of a string is O(n) in the worst case because all characters after the erased portion must be shifted left. Erasing from the end is O(1) if you use pop_back() or erase(size()-1). If you need to remove many characters scattered throughout, consider building a new string with only the characters you want to keep, which can be more efficient than repeated erase() calls.
For example, to remove all ‘a’ characters:
std::string s = "banana";
std::string result;
result.reserve(s.size()); // avoid reallocations
for (char c : s) {
if (c != 'a') result.push_back(c);
}
// result is "bnn"
This approach is O(n) and often faster than calling erase() in a loop, which would be O(n²) in the worst case due to repeated shifts.
Alternatives to erase()
Sometimes you do not need to modify the original string. Consider these alternatives:
substr(pos, count)– returns a new string with the specified portion, leaving the original unchanged.replace(pos, count, str)– replaces characters with another string, which can also effectively delete if you replace with an empty string.remove()anderase()idiom –std::removemoves non-matching characters to the front, then you callerase()to trim the tail. This is the standard way to remove all occurrences of a value efficiently.
std::string s = "banana";
s.erase(std::remove(s.begin(), s.end(), 'a'), s.end());
// s is now "bnn"
This works because std::remove returns an iterator to the new logical end, and erase() removes the rest.
Frequently Asked Questions
Does erase() invalidate iterators?
Yes. Any iterator or reference to an element at or after the erased position is invalidated. Only iterators before the erased position remain valid. This is important if you are looping and erasing; you must use the returned iterator to continue safely.
Can I erase a character by its value, like ‘x’?
There is no direct erase(value) overload. You must find the position first, for example with find(), then call erase(pos, 1). To erase all occurrences, use the std::remove idiom shown above.
What happens if pos is out of bounds?
If pos is greater than size(), the function throws std::out_of_range. If pos equals size(), it is valid but erases nothing. Always check your indices if they come from user input.
Does erase() work with wide strings (std::wstring)?
Yes, because std::wstring is a specialization of std::basic_string, so it has the same erase() overloads. The behavior is identical, just with wchar_t characters.
Is erase() the same as clear()?
No. clear() removes all characters, setting size to 0. erase() removes only a specified portion. You can achieve the same result with erase() by calling erase(0) or erase(begin(), end()), but clear() is clearer and more direct.