向量称为动态数组,可以在插入或删除元素时自动更改其大小。此存储由容器维护。
向量::: resize()
该函数在容器中插入或删除元素来实际更改容器的内容。碰巧是这样
- 如果给定的n值小于当前的大小,则将删除多余的元素。
- 如果n大于容器的当前大小,则即将出现的元素将附加到向量的末尾。
句法:
vectorname.resize(int n, int val)
- n – it is new container size, expressed in number of elements.
- val – if this parameter is specified then new elements are initialized with this value.
Return value:
- This function do not returns anything.
Exception:
- The only exception if it so happens is Bad_alloc thrown, if reallocation fails.
Parameters:
下面的程序说明了该函数的工作
- 矢量容器的尺寸减小了。
// resizing of the vector #include
#include using namespace std; int main() { vector vec; // 5 elements are inserted // in the vector vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); cout << "Contents of vector before resizing:" << endl; // displaying the contents of the // vector before resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; cout << endl; // vector is resized vec.resize(4); cout << "Contents of vector after resizing:" << endl; // displaying the contents of the // vector after resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; return 0; } 输出:
Contents of the vector before resizing: 1 2 3 4 5 Contents of the vector after resizing: 1 2 3 4
- 向量容器的尺寸增加。
// resizing of the vector #include
#include using namespace std; int main() { vector vec; // 5 elements are inserted // in the vector vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); cout << "Contents of vector before resizing:" << endl; // displaying the contents of the // vector before resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; cout << endl; // vector is resized vec.resize(8); cout << "Contents of vector after resizing:" << endl; // displaying the contents of // the vector after resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; return 0; } 输出:
Contents of the vector before resizing: 1 2 3 4 5 Contents of the vector after resizing: 1 2 3 4 5 0 0 0
- 向量容器的大小会增加,并使用指定的值初始化新元素。
// resizing of the vector #include
#include using namespace std; int main() { vector vec; // 5 elements are inserted // in the vector vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); cout << "Contents of vector before resizing:" << endl; // displaying the contents of // the vector before resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; cout << endl; // vector is resized vec.resize(12, 9); cout << "Contents of vector after resizing:" << endl; // displaying the contents // of the vector after resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; return 0; } 输出:
Contents of the vector before resizing: 1 2 3 4 5 Contents of the vector after resizing: 1 2 3 4 5 9 9 9 9 9 9 9
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。