命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | string‎ | basic_string
 
 
 
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) 移除范围 [firstlast) 中的字符。
firstlast 不是指向 *this有效迭代器,或 [firstlast) 不是有效范围,则行为未定义。

目录

[编辑] 参数

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

[编辑] 返回值

1) *this
2) 指向被擦除字符后紧跟的字符的迭代器,若不存在则为 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); // 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';
}

输出

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 没有异常安全保证 添加了强异常
安全保证

[编辑] 参阅

清除内容
(public member function) [编辑]