What is the usage of resize in vectors in C++?

In C++, the resize method of a vector is used to change the size of the vector. It has two different ways of usage.

  1. resize(n): Change the size of the vector to n. If n is greater than the current size of the vector, default-initialized elements will be inserted at the end. If n is smaller than the current size of the vector, excess elements will be removed.
std::vector<int> v = {1, 2, 3};
v.resize(5); // 现在v的大小为5,新增的元素为0
v.resize(2); // 现在v的大小为2,多余的元素被删除
  1. resize(n, val): Change the size of the vector to n. If n is larger than the current size of the vector, add elements with a value of val at the end. If n is smaller than the current size of the vector, remove any excess elements.
std::vector<int> v = {1, 2, 3};
v.resize(5, 0); // 现在v的大小为5,新增的元素为0
v.resize(2, 0); // 现在v的大小为2,多余的元素被删除

It’s important to note that the resize method will modify the size of the vector, potentially causing elements to be copied and memory to be reallocated. Therefore, when using the resize method, one should carefully consider the performance overhead.

bannerAds