简体   繁体   English

从向量错误C ++中删除元素

[英]Remove element from vector error C++

I know this might seem as a duplicate question, but it is not, I have a problem with a function and don''t know why it behaves like that. 我知道这似乎是一个重复的问题,但事实并非如此,我在使用函数时遇到了问题,也不知道为什么会这样。

I have a vector which holds elements of type MyMaterial** (std::vector). 我有一个向量,其中保存着MyMaterial **类型的元素(std :: vector)。 At a point in my program, I will know an element, "currentElement", and I will want to remove it. 在程序的一点上,我将知道一个元素“ currentElement”,并且希望将其删除。

I tried doing this: 我尝试这样做:

myMaterials.erase(currentElement);

But here is the problem: Instead of only deleting "currentElement", it also deletes all elements added after it. 但这是问题所在:它不仅删除“ currentElement”,还删除其后添加的所有元素。 Why does it do that and how can I solve it? 为什么这样做,我该如何解决?

I must mention that I don''t know the position of "currentElement" in the vector, and i prefere not to search for it, I''m hoping there is another way. 我必须提到,我不知道向量中“ currentElement”的位置,并且我不想搜索它,我希望有另一种方法。

If you are using std::vector, then: 如果您使用的是std :: vector,则:

Erase elements Removes from the vector either a single element (position) or a range of elements ([first,last)). 擦除元素从向量中删除单个元素(位置)或一系列元素([first,last))。

Maybe you are looking for something like this: 也许您正在寻找这样的东西:

How do I remove an item from a stl vector with a certain value? 如何从stl向量中删除具有特定值的项目?

To use vector::erase(iterator) to remove an element from a vector, you may either have to know its index OR iterate thru the list to hunt for it. 要使用vector::erase(iterator)从向量中删除元素,您可能必须知道其索引,或遍历列表以寻找它。

Luckily, There is the std::map, and this is how you would work it 幸运的是,这里有std :: map,这就是您的工作方式

std::map<std::string,myMaterial> myMaterials;
myMaterial mat;//assuming it doesnt take any args
myMaterials['myMaterialXYZ'] = mat; ///add it to the array
myMaterials.erase('myMaterialXYZ'); ///Erase by key..(or "name" in this case)

Now you can easily track string names instead of ever changing index positions...and memory locations, which by the way may be another ace up your sleeve. 现在,您可以轻松地跟踪字符串名称,而不用更改索引位置和存储位置,顺便说一句,这可能是您的另一个王牌。

I couldn''t really use the examples given by you above, because I got all kinds of errors, due to the type of elements the vector holds. 我不能真正使用上面您提供的示例,因为由于矢量所包含元素的类型,我遇到了各种各样的错误。 But I made a function which managed to delete the specific element: 但是我做了一个设法删除特定元素的函数:

int i=0;
int found=0;

MyMaterial **material = gMaterials.begin();
while(material != gMaterials.end() && found == 0)
{
  if(currentElement == material)
  {
    gMaterials.erase(gMaterials.begin() + i, gMaterials.begin() + i+1);
    found = 1;
  }
  i++;
  cloth++;
}

I don''t know how good/correct it is, but it does the job. 我不知道它有多好/正确,但确实可以。

Thank you very much for the suggestions and the help. 非常感谢您的建议和帮助。

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

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