C++ Vector 库 - resize() 函数
描述
C++ 函数 std::vector::resize() 改变向量的大小。如果 n 小于当前大小,则销毁额外的元素。
如果 n 大于当前容器大小,则在向量末尾插入新元素。
如果指定了 val,那么新元素将使用 val 进行初始化。
声明
以下是 std::vector::resize() 函数形式 std::vector 头的声明。
C++98
void resize (size_type n, value_type val = value_type());
C++11
void resize (size_type n); void resize (size_type n, const value_type& val);
参数
n − 新容器大小。
val − 容器元素的初始值。
返回值
None.
异常
如果重新分配失败,则抛出 bad_alloc 异常。
时间复杂度
线性,即 O(n)
示例
以下示例显示了 std::vector::resize() 函数的用法。
#include <iostream>
#include <vector>
using namespace std;
int main(void) {
vector<int> v;
cout << "Initial vector size = " << v.size() << endl;
v.resize(5, 10);
cout << "Vector size after resize = " << v.size() << endl;
cout << "Vector contains following elements" << endl;
for (int i = 0; i < v.size(); ++i)
cout << v[i] << endl;
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 −
Initial vector size = 0 Vector size after resize = 5 Vector contains following elements 10 10 10 10 10

