std::basic_string<CharT,Traits,Allocator>::erase

Removes specified characters from the string.

# Declarations

basic_string& erase( size_type index = 0, size_type count = npos );

(constexpr since C++20)

iterator erase( iterator position );

(until C++11)

iterator erase( const_iterator position );

(since C++11) (constexpr since C++20)

iterator erase( iterator first, iterator last );

(until C++11)

iterator erase( const_iterator first, const_iterator last );

(since C++11) (constexpr since C++20)

# Parameters

# Example

#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
 
int main()
{
    std::string s = "This Is An Example";
    std::cout << "1) " << s << '\n';
 
    s.erase(7, 3); // erases " An" using overload (1)
    std::cout << "2) " << s << '\n';
 
    s.erase(std::find(s.begin(), s.end(), ' ')); // erases first ' '; overload (2)
    std::cout << "3) " << s << '\n';
 
    s.erase(s.find(' ')); // trims from ' ' to the end of the string; overload (1)
    std::cout << "4) " << s << '\n';
 
    auto it = std::next(s.begin(), s.find('s')); // obtains iterator to the first 's'
    s.erase(it, std::next(it, 2)); // erases "sI"; overload (3)
    std::cout << "5) " << s << '\n';
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 27C++98overload (3) did not erase the character last pointed to, but it returnedthe iterator pointing to the character immediately following that characterreturns an iteratorpointing to that character
LWG 428C++98overload (2) explicitly required position to be valid, butSequenceContainer requires it to be dereferenceable (stricter)removed theexplicit requirement
LWG 847C++98there was no exception safety guaranteeadded strong exceptionsafety guarantee

# See also