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 中删除所有项目


基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30