resize函数
语法:
1 2 3 4 |
1.新元素数,元素值 void resize(size_type __new_size, const value_type& __x) 2.新元素数, void resize(size_type __new_size) |
resize() 改变Vector元素数量的大小
源代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
/** * @brief Resizes the %vector to the specified number of elements. * @param new_size Number of elements the %vector should contain. * @param x Data with which new elements should be populated. * * This function will %resize the %vector to the specified * number of elements. If the number is smaller than the * %vector's current size the %vector is truncated, otherwise * the %vector is extended and new elements are populated with * given data. */ void resize(size_type __new_size, const value_type& __x) { if (__new_size < size()) erase(begin() + __new_size, end()); else insert(end(), __new_size - size(), __x); } /** * @brief Resizes the %vector to the specified number of elements. * @param new_size Number of elements the %vector should contain. * * This function will resize the %vector to the specified * number of elements. If the number is smaller than the * %vector's current size the %vector is truncated, otherwise * the %vector is extended and new elements are * default-constructed. */ void resize(size_type __new_size) { resize(__new_size, value_type()); } |
测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
// 梁笔记 // https://zouzhongliang.com #include <iostream> #include <vector> using namespace std; int main() { vector<int> v1; vector<int> v2(3, 2); v1.push_back(1); v1.push_back(2); v1.push_back(3); v1.push_back(4); v1.push_back(5); cout<<"v1向量骨元素数:"<<v1.size()<<endl; cout<<"v2向量骨元素数:"<<v2.size()<<endl; //void resize(size_type __new_size) v1.resize(10); cout<<"v1向量骨元素数:"<<v1.size()<<endl; //void resize(size_type __new_size, const value_type& __x) v1.resize(8, 6); cout<<"v1向量骨元素数:"<<v1.size()<<endl; for(int i=0;i<v1.size();++i) cout<<v1[i]<<","; cout<<endl; } |
测试结果:
1 2 3 4 5 |
v1向量骨元素数:5 v2向量骨元素数:3 v1向量骨元素数:10 v1向量骨元素数:8 1,2,3,4,5,0,0,0, |