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++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
