std::forward_list<T,Allocator>::resize
來自 cppreference.com
< cpp | 容器 | forward_list
void resize( size_type count ); |
(1) | (C++11 起) |
void resize( size_type count, const value_type& value ); |
(2) | (C++11 起) |
重新調整容器大小以包含 count 個元素,如果 count == std::distance(begin(), end())(即如果 count 等於當前大小),則不執行任何操作。
如果當前大小大於 count,則容器將被縮小至其前 count 個元素。
如果當前大小小於 count,則
1) 將追加額外的 預設插入 元素。
2) 將追加 value 的額外副本。
目錄 |
[編輯] 引數
count | - | 容器的新大小 |
value | - | 用於初始化新元素的值 |
型別要求 | ||
-為了使用過載 (1),T 必須滿足 DefaultInsertable 的要求。 | ||
-為了使用過載 (2),T 必須滿足 CopyInsertable 的要求。 |
[編輯] 複雜度
時間複雜度為當前大小與 count 之間差值的線性關係。由於遍歷列表以到達要擦除的第一個元素/要插入的末尾位置,可能會增加額外的複雜度。
注意
如果過載 (1) 中的值初始化不符合預期,例如,如果元素是非類型別且不需要清零,則可以透過提供自定義的 Allocator::construct
來避免。
[編輯] 示例
執行此程式碼
#include <forward_list> #include <iostream> void print(auto rem, const std::forward_list<int>& c) { for (std::cout << rem; const int el : c) std::cout << el << ' '; std::cout << '\n'; } int main() { std::forward_list<int> c = {1, 2, 3}; print("The forward_list holds: ", c); c.resize(5); print("After resize up to 5: ", c); c.resize(2); print("After resize down to 2: ", c); c.resize(6, 4); print("After resize up to 6 (initializer = 4): ", c); }
輸出
The forward_list holds: 1 2 3 After resize up to 5: 1 2 3 0 0 After resize down to 2: 1 2 After resize up to 6 (initializer = 4): 1 2 4 4 4 4
[編輯] 另請參閱
返回元素的最大可能數量 (公共成員函式) | |
檢查容器是否為空 (公共成員函式) |