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

来自cppreference.com
< cpp‎ | string‎ | basic string
 
 
 
std::basic_string
 
template< container-compatible-range<CharT> R >
constexpr iterator insert_range( const_iterator pos, R&& rg );
(C++23 起)

pos 所指向的元素(如果有)之前插入范围 rg 中的字符。

等价于

return insert(pos - begin(),
    std::basic_string(
        std::from_range,
        std​::​forward<R>(rg),
        get_allocator())
);

如果 pos 不是 *this 上的有效迭代器,则其行为未定义。

目录

[编辑] 参数

pos - 迭代器,将在它之前插入字符
rg - 容器兼容范围

[编辑] 返回值

指代插入的第一个字符的迭代器,或者当 rg 为空而没有插入任何字符时为 pos

[编辑] 复杂度

rg 的大小成线性。

[编辑] 异常

如果 std::allocator_traits<Allocator>::allocate 抛出了异常,则它会被重新抛出。

如果操作会导致 size() 超出 max_size(),那么就会抛出 std::length_error

如果因为任何原因抛出了异常,那么此函数无效果(强异常安全保证)。

[编辑] 注解

功能特性测试 标准 功能特性
__cpp_lib_containers_ranges 202202L (C++23) 接受 容器兼容范围的成员函数

[编辑] 示例

#include <cassert>
#include <iterator>
#include <string>
 
int main()
{
    const auto source = {'l', 'i', 'b', '_'};
    std::string target{"__cpp_containers_ranges"};
    //                        ^将在此位置前进行插入
 
    const auto pos = target.find("container");
    assert(pos != target.npos);
    auto iter = std::next(target.begin(), pos);
 
#ifdef __cpp_lib_containers_ranges
    target.insert_range(iter, source);
#else
    target.insert(iter, source.begin(), source.end());
#endif
 
    assert(target == "__cpp_lib_containers_ranges");
    //                      ^^^^
}

[编辑] 参阅

插入字符
(公开成员函数) [编辑]