Namespaces
Variants

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

From cppreference.net
std::basic_string
basic_string & erase ( size_type index = 0 , size_type count = npos ) ;
(1) (自 C++20 起为 constexpr)
(2)
iterator erase ( iterator position ) ;
(C++11 前)
iterator erase ( const_iterator position ) ;
(自 C++11 起)
(自 C++20 起为 constexpr)
(3)
iterator erase ( iterator first, iterator last ) ;
(C++11 前)
iterator erase ( const_iterator first, const_iterator last ) ;
(自 C++11 起)
(自 C++20 起为 constexpr)

从字符串中移除指定字符。

1) index 开始移除 std:: min ( count, size ( ) - index ) 个字符。
2) 移除位于 position 处的字符。
如果 position 不是 * this 上的 可解引用迭代器 ,则行为未定义。
3) 移除范围 [ first , last ) 内的字符。
如果 first last 不是指向 * this 有效迭代器 ,或者 [ first , last ) 不是 有效范围 ,则行为未定义。

目录

参数

index - 要移除的第一个字符的位置
count - 要移除的字符数量
position - 指向要移除字符的迭代器
first, last - 要移除字符的范围

返回值

1) * this
2) 指向被擦除字符紧后字符的迭代器,若不存在此字符则返回 end()
3) 指向擦除前 last 所指向字符的迭代器,若该字符不存在则返回 end()

异常

1) std::out_of_range index > size ( )
2,3) 不抛出任何异常。

若因任何原因抛出异常,此函数不产生任何效果( 强异常安全保证 )。

示例

#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); // 使用重载(1)擦除" An"
    std::cout << "2) " << s << '\n';
    s.erase(std::find(s.begin(), s.end(), ' ')); // 擦除第一个空格;重载(2)
    std::cout << "3) " << s << '\n';
    s.erase(s.find(' ')); // 从空格开始截断到字符串末尾;重载(1)
    std::cout << "4) " << s << '\n';
    auto it = std::next(s.begin(), s.find('s')); // 获取指向第一个's'的迭代器
    s.erase(it, std::next(it, 2)); // 擦除"sI";重载(3)
    std::cout << "5) " << s << '\n';
}

输出:

1) This Is An Example
2) This Is Example
3) ThisIs Example
4) ThisIs
5) This

缺陷报告

以下行为变更缺陷报告被追溯应用于先前发布的C++标准。

缺陷报告 适用版本 发布时行为 正确行为
LWG 27 C++98 重载版本 ( 3 ) 未擦除 last 指向的字符,但返回
指向该字符紧后字符的迭代器
返回指向
该字符的迭代器
LWG 428 C++98 重载版本 ( 2 ) 显式要求 position 必须有效,但
SequenceContainer 要求其必须可解引用(更严格)
移除显式
要求
LWG 847 C++98 未提供异常安全保证 增加强异常
安全保证

参见

清空内容
(公开成员函数)