C++ List 库 - resize() 函数
描述
C++ 函数 std::list::resize() 改变列表的大小。 如果 n 小于当前大小,则销毁额外的元素。如果 n 大于当前容器大小,则在列表末尾插入新元素。
声明
以下是 std::list::resize() 函数形式 std::list 头的声明。
C++11
void resize (size_type n);
参数
n − 要插入的元素数。
返回值
None
异常
如果重新分配失败,则抛出 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

