std::inplace_vector<T,N>::assign
來自 cppreference.com
< cpp | 容器 | inplace_vector
constexpr void assign( size_type count, const T& value ); |
(1) | (C++26 起) |
template< class InputIt > constexpr void assign( InputIt first, InputIt last ); |
(2) | (C++26 起) |
constexpr void assign( std::initializer_list<T> ilist ); |
(3) | (C++26 起) |
替換容器的內容。
1) 將內容替換為 count 個 value 的副本。
2) 將內容替換為範圍
[
first,
last)
中元素的副本。3) 將內容替換為 ilist 中的元素。
本節不完整 |
目錄 |
[編輯] 引數
count | - | 容器的新大小 |
value | - | 用於初始化容器元素的數值 |
first, last | - | 定義要複製的元素的源 範圍 的迭代器對 |
ilist | - | std::initializer_list,從中複製值 |
[編輯] 複雜度
1) 關於 count 的線性複雜度。
2) 關於 first 和 last 之間距離的線性複雜度。
3) 關於 ilist.size() 的線性複雜度。
異常
1-3) 插入元素初始化時丟擲的任何異常。
[編輯] 示例
以下程式碼使用 assign
向 std::inplace_vector<char, 5> 新增多個字元
執行此程式碼
#include <inplace_vector> #include <iterator> #include <new> #include <print> int main() { std::inplace_vector<char, 5> chars; chars.assign(4, 'a'); // overload (1) std::println("{}", chars); const char extra[3]{'a', 'b', 'c'}; chars.assign(std::cbegin(extra), std::cend(extra)); // overload (2) std::println("{}", chars); chars.assign({'C', '+', '+', '2', '6'}); // overload (3) std::println("{}", chars); try { chars.assign(8, 'x'); // throws: count > chars.capacity() } catch(const std::bad_alloc&) { std::println("std::bad_alloc #1"); } try { const char bad[8]{'?'}; // ranges::distance(bad) > chars.capacity() chars.assign(std::cbegin(bad), std::cend(bad)); // throws } catch(const std::bad_alloc&) { std::println("std::bad_alloc #2"); } try { const auto l = {'1', '2', '3', '4', '5', '6'}; chars.assign(l); // throws: l.size() > chars.capacity() } catch(const std::bad_alloc&) { std::println("std::bad_alloc #3"); } }
輸出
['a', 'a', 'a', 'a'] ['a', 'b', 'c'] ['C', '+', '+', '2', '6'] std::bad_alloc #1 std::bad_alloc #2 std::bad_alloc #3
[編輯] 參閱
將一個範圍的值賦給容器 (public member function) | |
將值賦給容器 (public member function) |