C++ forward_list 庫 - resize() 函式



描述

C++ 函式std::forward_list::resize() 改變 forward_list 的大小。如果n小於當前大小,則額外的元素將被銷燬。如果n大於當前容器大小,則新的元素將被插入到 forward_list 的末尾。

宣告

以下是來自 std::forward_list 標頭檔案的 std::forward_list::resize() 函式宣告。

C++11

void resize (size_type n);

引數

n − 要插入的元素個數。

返回值

異常

如果重新分配失敗,則bad_alloc異常將被丟擲。

時間複雜度

線性,即 O(n)

示例

以下示例演示了 std::forward_list::resize() 函式的使用。

#include <iostream>
#include <forward_list>

using namespace std;

bool foo(int n) {
   return (n > 5);
}

int main(void) {

   forward_list<int> fl;

   fl.resize(5);

   cout << "List contents after resize operation" << endl;

   for (auto it = fl.begin(); it != fl.end(); ++it)
      cout << *it << endl;

   return 0;
}

讓我們編譯並執行上面的程式,這將產生以下結果:

List contents after resize operation
0
0
0
0
0
forward_list.htm
廣告
© . All rights reserved.