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

来自cppreference.com
< cpp‎ | string‎ | basic string
 
 
 
std::basic_string
成员函数
元素访问
迭代器
容量
操作
basic_string::erase
搜索
常量
推导指引 (C++17)
非成员函数
I/O
比较
(C++20 前)(C++20 前)(C++20 前)(C++20 前)(C++20 前)(C++20)
数值转换
(C++11)(C++11)(C++11)
(C++11)(C++11)
(C++11)(C++11)(C++11)
(C++11)
(C++11)
辅助类
 
(1)
basic_string& erase( size_type index = 0, size_type count = npos );
(C++20 前)
constexpr basic_string& erase( size_type index = 0, size_type count = npos );
(C++20 起)
(2)
iterator erase( iterator position );
(C++11 前)
iterator erase( const_iterator position );
(C++11 起)
(C++20 前)
constexpr iterator erase( const_iterator position );
(C++20 起)
(3)
iterator erase( iterator first, iterator last );
(C++11 前)
iterator erase( const_iterator first, const_iterator last );
(C++11 起)
(C++20 前)
constexpr iterator erase( const_iterator first, const_iterator last );
(C++20 起)

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

1) 移除从 index 开始的 std::min(count, size() - index) 个字符。
2) 移除位于 position 的字符。
3) 移除范围 [first, last) 中的字符。

参数

index - 要移除的首个字符
count - 要移除的字符数
position - 指向要移除的字符的迭代器
first, last - 要移除的字符范围

返回值

1) *this
2) 指向立即后随被擦除字符的迭代器,或者在不存在这种字符的情况下返回 end()
3) 指向擦除前 last 指向的字符的迭代器,或者在不存在这种字符的情况下 end()

异常

1)index > size() 时抛出 std::out_of_range
2-3) 不抛出。

在任何情况下,如果因为任何原因抛出异常,那么此函数无效果(强异常保证)。

(C++11 起)

示例

#include <iostream>
#include <algorithm>
#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)); // 使用重载 (3) 擦除 "sI"
    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 指向的字符,但它返回了指向立即后随该字符的迭代器 返回指向该字符的迭代器

参阅

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