清空向量的特定元素
我想将向量的特定位置处的元素设置为空,因此可以按如下方式执行
vector<IXMLDOMNodePtr> vec1;// filled somehow
vec1[i] = nullptr;// some specific position i
:我想保留为空的条目,它的作用就像占位符,所以我想也许 vec[i] = 0
可以吗?
I want to set an element at a specific position of a vector to null, so can do it as the following:
vector<IXMLDOMNodePtr> vec1;// filled somehow
vec1[i] = nullptr;// some specific position i
ps. I want to keep the entry that is nulled, which acts like a place holder, so I think maybe vec[i] = 0
will do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
要删除元素(如果这就是
NULL
的意思),您可以使用vector::erase
或者,创建一个
IXMLDOMNodePtr
的虚拟对象,根据您的编码标准,该对象被视为 NULL,并设置该对象:为此你需要超载
IXMLDOMNodePtr::operator ==
。For removal of the element (if that's what you mean by
NULL
) you can usevector::erase
Or else, create a dummy object of
IXMLDOMNodePtr
, which is considered a NULL according to your coding standard and set that object:For that you need to overload
IXMLDOMNodePtr::operator ==
.可能
erase()
会有所帮助,例如,当您迭代下一个时,该条目将不存在...
现在我们知道您想要做什么,这样的事情应该可以工作..
这不知道这个
IXMLDOMNodePtr
是什么(如果它是顾名思义的指针),那么只需将其设置为0
就可以了。注意:如果动态分配此对象,将其设置为
0
不会像在 Java 中将某些内容设置为null
那样清除内存 - 在 C++ 中,您必须显式清理它首先,即May be
erase()
will help, e.g.When you iterate through next, that entry will not be there...
Now that we know what you want to do, something like this ought to work..
This is without knowing what this
IXMLDOMNodePtr
is (if it is as the name implies a pointer), then simply setting it to0
ought to work.NOTE: If you dynamically allocated this object, setting it to
0
does not clear up the memory as setting something tonull
does in Java - in C++ you have to explicitly clean it up first, i.e.不会。向量在设计上是连续的。这意味着
.size()==5
的向量具有[0]
到[4]
元素。您可能需要一个
std::map
:No. A vector is contiguous by design. That means that a vector with
.size()==5
has elements[0]
to[4]
.You may want a
std::map<int, IXMLDOMNodePtr>
:使用
vec1.resize(whatever_size_you_need);
,它将扩展向量并将每个元素默认为0。然后您可以根据需要使用[]
。Use
vec1.resize(whatever_size_you_need);
and it will expand the vector and default each element to 0. Then you can use[]
as much as you want.您可以使用 vec1.erase((vec1.begin()+i); 删除向量的第 i 个元素。之后 vec1.size() 减 1,所以如果您必须编写一个循环来擦除向量的某些元素,一个好的做法是使用向后循环;)
You can use
vec1.erase((vec1.begin()+i);
to erase the i-th element of the vector. After that vec1.size() is reduced by 1, so if you have to write a cycle that erases some elements of the vector, a good practice is to use a backwards cycle ;)不,你不能。您需要初始化向量以包含元素
或推回空元素
no you can't. you need to initialize the vector to have element
or push back null elements