名前空間
変種
操作

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

From cppreference.com
< cpp‎ | string‎ | basic string
 
 
 
std::basic_string
 
template< class container-compatible-range<CharT> R >

constexpr std::basic_string& replace_with_range( const_iterator first,
                                                 const_iterator last,

                                                 R&& rg );
(C++23から)

範囲 [firstlast) の文字を、範囲 rg の文字で置き換えます。

以下と等価です。

return replace(first,
               last,
               std::basic_string(
                   std::from_range,
                   std::forward<R>(rg),
                   get_allocator())
);

目次

[編集] パラメータ

first, last - 置き換えられる文字の範囲
rg - a コンテナ互換範囲

[編集] 戻り値

*this

[編集] 計算量

rg のサイズに対して線形。

[編集] 例外

操作によりsize()max_size()を超える場合、std::length_errorを送出します。

何らかの理由で例外がスローされた場合、この関数は効果がありません(強力な例外安全保証)。

[編集] 注記

機能テストマクロ 規格 機能
__cpp_lib_containers_ranges 202202L (C++23) コンテナ互換範囲を受け入れるメンバ関数

[編集]

#include <algorithm>
#include <cassert>
#include <forward_list>
#include <iterator>
#include <string>
 
int main()
{
    using namespace std::literals;
 
    auto s{"Today is today!"s};
    constexpr auto today{"today"sv};
    constexpr auto tomorrow{"tomorrow's yesterday"sv};
    std::forward_list<char> rg;
    std::ranges::reverse_copy(tomorrow, std::front_inserter(rg));
 
    const auto pos{s.rfind(today)};
    assert(pos != s.npos);
    const auto first{std::next(s.begin(), pos)};
    const auto last{std::next(first, today.length())};
 
#ifdef __cpp_lib_containers_ranges
    s.replace_range(first, last, rg);
#else
    s.replace(first, last, rg.cbegin(), rg.cend());
#endif
 
    assert("Today is tomorrow's yesterday!" == s);
}

[編集] 関連項目

文字列の指定された部分を置換する
(public member function) [編集]
English 日本語 中文(简体) 中文(繁體)