命名空间
变体
操作

std::inplace_vector<T,N>::insert

来自 cppreference.cn
 
 
 
 
constexpr iterator insert( const_iterator pos, const T& value );
(1) (自 C++26 起)
constexpr iterator insert( const_iterator pos, T&& value );
(2) (自 C++26 起)
constexpr iterator insert( const_iterator pos, size_type count, const T& value );
(3) (自 C++26 起)
template< class InputIt >
constexpr iterator insert( const_iterator pos, InputIt first, InputIt last );
(4) (自 C++26 起)
constexpr iterator insert( const_iterator pos, std::initializer_list<T> ilist );
(5) (自 C++26 起)

在容器的指定位置插入元素。

1)pos 之前插入 value 的副本。
2)pos 之前插入 value,可能使用移动语义。
3)pos 之前插入 countvalue 的副本。
4)pos 之前插入范围 [firstlast) 中的元素。仅当 InputItLegacyInputIterator 时,此重载才参与重载解析(以避免与重载 (3) 混淆)。
[firstlast) 中的每个迭代器都会被解引用一次。
如果 firstlast 是指向 *this 的迭代器,则行为未定义。
5)pos 之前插入初始化列表 ilist 中的元素。等效于:insert(pos, ilist.begin(), ilist.end());

目录

[edit] 参数

pos - 内容将被插入之前的迭代器(pos 可以是 end() 迭代器)
value - 要插入的元素值
count - 要插入的元素数量
first, last - 定义要插入元素的源范围的迭代器对
ilist - std::initializer_list,从中插入值
类型要求
-
T 必须满足 CopyInsertable 的要求才能使用重载 (1)。
-
T 必须满足 MoveInsertable 的要求才能使用重载 (2)。
-
T 必须满足 CopyAssignableCopyInsertable 的要求才能使用重载 (3)。
-
T 必须满足 EmplaceConstructible 的要求才能使用重载 (4,5)。

[edit] 返回值

1,2) 指向插入的 value 的迭代器。
3) 指向第一个插入元素的迭代器;如果 count == 0,则为 pos
4) 指向第一个插入元素的迭代器;如果 first == last,则为 pos
5) 指向第一个插入元素的迭代器;如果 ilist 为空,则为 pos

[edit] 复杂度

与插入元素的数量加上 pos 与容器的 end() 之间的距离成线性关系。

[edit] 异常

[edit] 示例

#include <initializer_list>
#include <inplace_vector>
#include <iterator>
#include <new>
#include <print>
 
int main()
{
    std::inplace_vector<int, 14> v(3, 100);
    std::println("1. {}", v);
 
    auto pos = v.begin();
    pos = v.insert(pos, 200); // overload (1)
    std::println("2. {}", v);
 
    v.insert(pos, 2, 300); // overload (3)
    std::println("3. {}", v);
 
    int arr[] = {501, 502, 503};
    v.insert(v.begin(), arr, arr + std::size(arr)); // overload (4)
    std::println("4. {}", v);
 
    v.insert(v.end(), {601, 602, 603}); // overload (5)
    std::println("5. {}", v);
 
    const auto list = {-13, -12, -11};
    try
    {
        v.insert(v.begin(), list); // throws: no space
    }
    catch(const std::bad_alloc&)
    {
        std::println("bad_alloc: v.capacity()={} < v.size()={} + list.size()={}",
                     v.capacity(), v.size(), list.size());
    }
}

输出

1. [100, 100, 100]
2. [200, 100, 100, 100]
3. [300, 300, 200, 100, 100, 100]
4. [501, 502, 503, 300, 300, 200, 100, 100, 100]
5. [501, 502, 503, 300, 300, 200, 100, 100, 100, 601, 602, 603]
bad_alloc: v.capacity()=14 < v.size()=12 + list.size()=3

[edit] 参见

就地构造元素
(公共成员函数) [编辑]
插入一系列元素
(公共成员函数) [编辑]