std::basic_string<CharT,Traits,Allocator>::erase
來自 cppreference.com
< cpp | string | 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) |
|
從字串中移除指定字元。
2) 移除 position 處的字元。
3) 移除範圍
[
first,
last)
中的字元。目錄 |
[編輯] 引數
index | - | 要移除的起始字元 |
count | - | 要移除的字元數 |
position | - | 指向要移除的字元的迭代器 |
first, last | - | 要移除的字元範圍 |
[編輯] 返回值
1) *this
2) 指向被擦除字元後緊跟的字元的迭代器,若不存在則為 end()。
[編輯] 異常
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) |