Delete all items from a c++ std::vector(从 c++ std::vector 中删除所有项目)
问题描述
我正在尝试使用以下代码从 std::vector
中删除所有内容
I'm trying to delete everything from a std::vector
by using the following code
vector.erase( vector.begin(), vector.end() );
但它不起作用.
更新:不清除破坏向量持有的元素?我不想那样,因为我还在使用对象,我只想清空容器
Update: Doesn't clear destruct the elements held by the vector? I don't want that, as I'm still using the objects, I just want to empty the container
推荐答案
我认为你应该使用 std::vector::clear
:
I think you should use std::vector::clear
:
vec.clear();
<小时>
不清除破坏元素由向量持有?
Doesn't clear destruct the elements held by the vector?
是的.它在返回内存之前调用向量中每个元素的析构函数.这取决于您在向量中存储的元素".在以下示例中,我将对象本身存储在向量中:
Yes it does. It calls the destructor of every element in the vector before returning the memory. That depends on what "elements" you are storing in the vector. In the following example, I am storing the objects them selves inside the vector:
class myclass
{
public:
~myclass()
{
}
...
};
std::vector<myclass> myvector;
...
myvector.clear(); // calling clear will do the following:
// 1) invoke the deconstrutor for every myclass
// 2) size == 0 (the vector contained the actual objects).
例如,如果您想在不同容器之间共享对象,则可以存储指向它们的指针.在这种情况下,当调用 clear
时,只释放指针内存,不接触实际对象:
If you want to share objects between different containers for example, you could store pointers to them. In this case, when clear
is called, only pointers memory is released, the actual objects are not touched:
std::vector<myclass*> myvector;
...
myvector.clear(); // calling clear will do:
// 1) ---------------
// 2) size == 0 (the vector contained "pointers" not the actual objects).
对于评论中的问题,我认为getVector()
是这样定义的:
For the question in the comment, I think getVector()
is defined like this:
std::vector<myclass> getVector();
也许你想返回一个引用:
Maybe you want to return a reference:
// vector.getVector().clear() clears m_vector in this case
std::vector<myclass>& getVector();
这篇关于从 c++ std::vector 中删除所有项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 c++ std::vector 中删除所有项目
基础教程推荐
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 从 std::cin 读取密码 2021-01-01