std::inplace_vector<T,N>::insert
來自 cppreference.com
< 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) |