简体   繁体   English

从向量 C++ 中擦除 class 元素

[英]Erasing a class element from the vector C++

I've faced a problem when I've tried to erase an element from the vector.当我试图从向量中删除一个元素时,我遇到了一个问题。 Vector is filled with Class elements (class is called Node).向量填充了 Class 元素(类称为节点)。 So I've tried this:所以我试过这个:

int index = 2;
vector<Node> openNodesSet;
openNodesSet.erase(index);

But this is not working.但这不起作用。 I've found a solution:我找到了一个解决方案:

int index = 2;
vector<Node> openNodesSet;
vector<Node>::iterator it = openNodesSet.begin();
advance(it, lowestIndex);
openNodesSet.erase(it);

Could somebody explane me why the first way is not working and the second one works without any problem?有人可以解释一下为什么第一种方法不起作用而第二种方法没有任何问题吗? Is there any other ways to remove an element from the vector?有没有其他方法可以从向量中删除元素?

It's because erase takes an iterator as parameter, so if you want to work with your first try:这是因为eraseiterator作为参数,所以如果你想使用你的第一次尝试:

int index = 2;
vector<Node> openNodesSet;
openNodesSet.erase(openNodeSet.begin()+index);

As the vector::erase() doc say:正如vector::erase() 文档所说:

iterator erase( iterator pos );
iterator erase( const_iterator pos );
Parameters参数
pos - iterator to the element to remove pos -要删除的元素的迭代器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM