std::basic_string<CharT,Traits,Allocator>::erase
来自cppreference.com
<tbody>
</tbody>
<tbody class="t-dcl-rev t-dcl-rev-num ">
</tbody><tbody>
</tbody>
<tbody class="t-dcl-rev t-dcl-rev-num ">
</tbody><tbody>
</tbody>
<tbody class="t-dcl-rev t-dcl-rev-num ">
</tbody><tbody>
</tbody>
| (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)
*this2) 指向紧跟被擦除字符之后的迭代器,或者在不存在这种字符的情况下返回 end()。
3) 指向擦除前
last 指向的字符的迭代器,或者在不存在这种字符的情况下返回 end()。异常
1) 在
index > size() 时抛出 std::out_of_range。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)); // 使用重载 (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 指向的字符,但它返回了指向立即后随该字符的迭代器
|
返回指向该字符的迭代器 |
| LWG 428 | C++98 | 重载 (2) 显式要求 position 合法,但序列容器 (SequenceContainer) 要求它可解引用(更严格) |
移除该显式要求 |
| LWG 847 | C++98 | 没有异常安全保证 | 添加强异常安全保证 |
参阅
| 清除内容 (公开成员函数) |