std::inplace_vector<T,N>::insert
来自 cppreference.cn
< cpp | 容器 | inplace_vector
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 之前插入 count 个 value 的副本。
[
first,
last)
中的每个迭代器都被解引用一次。 如果 first 和 last 是指向 *this 的迭代器,则行为是未定义的。
5) 在 pos 之前插入来自初始化列表 ilist 的元素。等价于: insert(pos, ilist.begin(), ilist.end());。
本节不完整 |
目录 |
[编辑] 参数
pos | - | 内容将被插入之前的迭代器(pos 可以是 end() 迭代器) |
value | - | 要插入的元素值 |
count | - | 要插入的元素数量 |
first, last | - | 定义要插入的元素源范围的迭代器对 |
ilist | - | 要从中插入值的 std::initializer_list |
类型要求 | ||
-为了使用重载 (1),T 必须满足CopyInsertable的要求。 | ||
-为了使用重载 (2),T 必须满足MoveInsertable的要求。 | ||
-为使用重载 (3),T 必须满足 CopyAssignable 和 CopyInsertable 的要求。 | ||
-为使用重载 (4,5),T 必须满足 EmplaceConstructible 的要求。 |
[编辑] 返回值
1,2) 指向插入的 value 的迭代器。
3) 指向插入的第一个元素的迭代器,如果 count == 0,则为 pos。
4) 指向插入的第一个元素的迭代器,如果 first == last,则为 pos。
5) 指向插入的第一个元素的迭代器,如果 ilist 为空,则为 pos。
[编辑] 复杂度
与插入的元素数量加上 pos 和容器的 end()
之间的距离呈线性关系。
[编辑] 异常
- 如果在调用前 size() == capacity(),则抛出 std::bad_alloc。该函数无任何效果(强异常安全保证)。
- 插入元素的初始化或任何 LegacyInputIterator 操作抛出的任何异常。范围
[
0,
pos)
中的元素未被修改。
[编辑] 示例
运行此代码
#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
[编辑] 参阅
就地构造元素 (public member function) | |
插入元素范围 (public member function) |