简体   繁体   中英

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). At a point in my program, I will know an element, "currentElement", and I will want to remove it.

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. 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.

If you are using std::vector, then:

Erase elements Removes from the vector either a single element (position) or a range of elements ([first,last)).

Maybe you are looking for something like this:

How do I remove an item from a stl vector with a certain value?

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.

Luckily, There is the std::map, and this is how you would work it

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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