C++ 列表庫 - resize() 函式



描述

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

宣告

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

C++11

void resize (size_type n);

引數

n − 要插入的元素數量。

返回值

異常

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

時間複雜度

線性,即 O(n)

示例

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

#include <iostream>
#include <list>

using namespace std;

int main(void) {
   list<int> l;

   cout << "Initial size of list = " << l.size() << endl;

   l.resize(5);

   cout << "Size of list after resize operation = " << l.size() << endl;

   cout << "List contains following elements" << endl;

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

   return 0;
}

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

Initial size of list = 0
Size of list after resize operation = 5
List contains following elements
0
0
0
0
0
list.htm
廣告
© . All rights reserved.