vector :: resize()是“ vector”标头的库函数,用于调整矢量的大小,它接受更新的元素数量和默认值(可选),并调整矢量容器的大小。
注意:要使用向量,请包含<vector>标头。
vector :: resize()函数的语法
vector::resize();
参数: n –是更新的大小,val –是要分配给新大小的默认值,value_type()–它是容器的值类型(引用第一个模板参数的类型) )。
返回值: void –不返回任何内容。
示例
Input: vector<int> vector1{ 1, 2, 3, 4, 5 }; Function call: cout << vector1.resize(10); Output: //如果我们打印元素 1 2 3 4 5 0 0 0 0 0
//C ++ STL程序演示示例 //vector :: resize()函数 #include <iostream> #include <vector> using namespace std; int main(){ vector<int> v1; //打印向量的大小 cout << "Total number of elements: " << v1.size() << endl; //推动元素 v1.push_back(10); v1.push_back(20); v1.push_back(30); v1.push_back(40); v1.push_back(50); //打印向量的大小 cout << "Total number of elements: " << v1.size() << endl; //打印元素 cout << "vector elements are: "; for (int x : v1) cout << x << " "; cout << endl; //使用默认值调整大小 //并打印元素 v1.resize(8, 99); //打印向量的大小 cout << "Total number of elements: " << v1.size() << endl; //打印元素 cout << "vector elements are: "; for (int x : v1) cout << x << " "; cout << endl; //调整大小而没有默认值 //并打印元素 v1.resize(10); //打印向量的大小 cout << "Total number of elements: " << v1.size() << endl; //打印元素 cout << "vector elements are: "; for (int x : v1) cout << x << " "; cout << endl; return 0; }
输出结果
Total number of elements: 0 Total number of elements: 5 vector elements are: 10 20 30 40 50 Total number of elements: 8 vector elements are: 10 20 30 40 50 99 99 99 Total number of elements: 10 vector elements are: 10 20 30 40 50 99 99 99 0 0
参考:C ++ vector :: resize()