菜鸟笔记
提升您的技术认知

vector中resize() 用法排坑

vector中resize() 用法排坑

先赞后看,养成好习惯。有帮助的话,点波关注!我会坚持更新,感谢谢您的支持!

参考
std::vector::resize

需求: 调试程序出现一个vector置0的问题,最后定位到是resize使用不当,以此记录。

情况简化说明

1. 初始化vector,然后想用resize()为所有元素赋值

vector<int> test = {0,1,2,3,4};
test.resize(10,0);
// 打印结果
for(const auto &value: test) std::cout << value << ","; 
std::cout << std::endl;

通常以为打印结果为10个0, 但是实际为0,1,2,3,4,0,0,0,0,0,

2. resize()函数说明

2.1 函数原型(C++11)

void resize (size_type n);
void resize (size_type n, const value_type& val);

2.2 官方解释

Resizes the container so that it contains n elements.

If n is smaller than the current container size, the content is reduced to its first n elements, removing those beyond (and destroying them).

If n is greater than the current container size, the content is expanded by inserting at the end as many elements as needed to reach a size of n. If val is specified, the new elements are initialized as copies of val, otherwise, they are value-initialized.

If n is also greater than the current container capacity, an automatic reallocation of the allocated storage space takes place.

Notice that this function changes the actual content of the container by inserting or erasing elements from it.

2.3 用法说明

  • 调整容器大小,使其包含n个元素
  • 如果 n 小于当前容器大小,则内容将减少到它的前 n 个元素,删除超出的那些(并释放它们)。
  • 如果 n 大于当前容器大小,则通过在末尾插入所需数量的元素来扩展内容,以达到 n 的大小。 如果指定了 val,则将新元素初始化为 val 的副本,否则,将它们初始化为0。
  • 如果 n 也大于当前容器容量,则会自动重新分配已分配的存储空间。

注意,此函数通过插入或删除元素来更改容器的实际内容。

2.4 实践举例

借用官方的例子。

// resizing vector
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector;

  // set some initial content:
  for (int i=1;i<10;i++) myvector.push_back(i);

  myvector.resize(5);
  myvector.resize(8,100);
  myvector.resize(12);

  std::cout << "myvector contains:";
  for (int i=0;i<myvector.size();i++)
    std::cout << ' ' << myvector[i];
  std::cout << '\n';

  return 0;
}

结果
myvector contains: 1 2 3 4 5 100 100 100 0 0 0 0

解释

  • 初始化9个元素,从1到9。
  • 第一个操作resize(5),会删除最后的4个元素,此时剩下1 2 3 4 5。
  • 第二个操作resize(8,100),会在尾部插入3个元素,3个元素值为100。
  • 第三个操作resize(12),会再次再尾部插入12-8=4个元素,元素因为没有提供初始值,故采用默认的0。

2.5 拓展

项目中的真实需求是在程序开始位置,每次将成员变量vector中的所有元素置为0,最终采用std::fill() 填充函数,clear()会清空数值,但是不释放内存。

std::fill(input_data_.begin(), input_data_.end(), 0);  // 填充
input_data_.clear(); // 清空后,遍历打印则看不到结果