名前空間
変種
操作

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

From cppreference.com
< 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) std::min(count, size() - index) 文字を index から削除します。
2) position の文字を削除します。
position*this逆参照可能なイテレータでない場合、動作は未定義です。
3) [firstlast) の範囲の文字を削除します。
first または last*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 例外安全性保証がなかった 強力な例外安全保証
を追加

[編集] 関連項目

内容をクリアする
(public member function) [編集]
English 日本語 中文(简体) 中文(繁體)