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
广告