为什么在向量向量上使用的 clear() 不会清除这些向量的值? [英] Why clear() used on vector of vectors doesn't clear the values of those vectors?

查看:49
本文介绍了为什么在向量向量上使用的 clear() 不会清除这些向量的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我非常确定 vector 调用了所包含对象的析构函数,所以我只是在主向量上使用了 clear(),然后我重用了该向量,并且存储在其中的向量的值没有被清除...

I was so sure that vector calls the destructors of the contained objects that I just used the clear() on the main vector and then I reused the vector and the values of the vectors stored in it were not cleared...

编辑 - 代码:

vector<vector<int> > flush1;
flush1.reserve(4);
for(int i = 0; i != 4; ++i) flush1[i].reserve(7);
flush1.clear();
flush1[0].push_back(some_int);
flush1[1].push_back(some_int);
flush1[2].push_back(some_int);
flush1[3].push_back(some_int);
cout the size from flush1[0-3];
flush1.clear();

又一次

flush1[0].push_back(some_int);
flush1[1].push_back(some_int);
flush1[2].push_back(some_int);
flush1[3].push_back(some_int);

并从flush1[0-3] cout-s 他们以前的大小+新的大小(旧的和新的相加)中计算大小

and cout-ing the size from flush1[0-3] cout-s their previous size + new sizes (addition of old and new)

推荐答案

vector 对象具有三个指针:开始、结束和保留存储结束.

The vector object has three pointers: the beginning, the end and end-of-reserved-storage.

clear() 方法对每个包含的对象调用析构函数,然后将结束指针设置为开始.

The clear() method calls the destructor on each contained object and then sets the end pointer to the beginning.

因此被破坏的对象的数据在保留存储中仍然可见(例如使用调试器).

So the data of the destructed objects will still be visible (using a debugger for example) in the reserved storage.

这篇关于为什么在向量向量上使用的 clear() 不会清除这些向量的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆