Namespaces
Variants

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

From cppreference.net
std::basic_string
template < container-compatible-range < CharT > R >

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

R && rg ) ;
(C++23以降)

範囲 [ first , last ) 内の文字を、範囲 rg からの文字で置き換えます。

次と同等

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

目次

パラメータ

first, last - 置換対象となる文字の範囲
rg - container compatible range

戻り値

* this

計算量

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

例外

操作によって size() max_size() を超える場合、 std::length_error をスローします。

何らかの理由で例外がスローされた場合、この関数は何も効果を持ちません( strong exception safety guarantee )。

注記

機能テスト マクロ 標準 機能
__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);
}

関連項目

文字列の指定された部分を置換する
(公開メンバ関数)