命名空间
变体
操作

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) (constexpr 自 C++20 起)
(2)
iterator erase( iterator position );
(C++11 前)
iterator erase( const_iterator position );
(自 C++11 起)
(constexpr 自 C++20 起)
(3)
iterator erase( iterator first, iterator last );
(C++11 前)
iterator erase( const_iterator first, const_iterator last );
(自 C++11 起)
(constexpr 自 C++20 起)

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

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++ 标准。

DR 应用于 已发布行为 正确行为
LWG 27 C++98 重载 (3) 没有移除 last 指向的字符,但它返回
指向紧随该字符之后的字符的迭代器
返回一个迭代器
指向该字符
LWG 428 C++98 重载 (2) 显式要求 position 有效,但
SequenceContainer 要求它是可解引用的(更严格)
移除了
显式要求
LWG 847 C++98 没有异常安全保证 添加了强异常
安全保证

[编辑] 参见

清除内容
(公共成员函数) [编辑]