先赞后看,养成好习惯。有帮助的话,点波关注!我会坚持更新,感谢谢您的支持!
需求: 调试程序出现一个vector置0的问题,最后定位到是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,
- void resize (size_type n);
- void resize (size_type n, const value_type& val);
- 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.
删除
超出的那些(并释放它们)。插入
所需数量的元素来扩展内容,以达到 n 的大小。 如果指定了 val,则将新元素初始化为 val 的副本,否则,将它们初始化为0。注意,此函数通过插入或删除
元素来更改容器的实际内容。
借用官方的例子。
- // 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
解释:
项目中的真实需求是在程序开始位置,每次将成员变量vector中的所有元素置为0,最终采用std::fill()
填充函数,clear()
会清空数值,但是不释放内存。
- std::fill(input_data_.begin(), input_data_.end(), 0); // 填充
- input_data_.clear(); // 清空后,遍历打印则看不到结果