簡體   English   中英

從向量錯誤C ++中刪除元素

[英]Remove element from vector error C++

我知道這似乎是一個重復的問題,但事實並非如此,我在使用函數時遇到了問題,也不知道為什么會這樣。

我有一個向量,其中保存着MyMaterial **類型的元素(std :: vector)。 在程序的一點上,我將知道一個元素“ currentElement”,並且希望將其刪除。

我嘗試這樣做:

myMaterials.erase(currentElement);

但這是問題所在:它不僅刪除“ currentElement”,還刪除其后添加的所有元素。 為什么這樣做,我該如何解決?

我必須提到,我不知道向量中“ currentElement”的位置,並且我不想搜索它,我希望有另一種方法。

如果您使用的是std :: vector,則:

擦除元素從向量中刪除單個元素(位置)或一系列元素([first,last))。

也許您正在尋找這樣的東西:

如何從stl向量中刪除具有特定值的項目?

要使用vector::erase(iterator)從向量中刪除元素,您可能必須知道其索引,或遍歷列表以尋找它。

幸運的是,這里有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)

現在,您可以輕松地跟蹤字符串名稱,而不用更改索引位置和存儲位置,順便說一句,這可能是您的另一個王牌。

我不能真正使用上面您提供的示例,因為由於矢量所包含元素的類型,我遇到了各種各樣的錯誤。 但是我做了一個設法刪除特定元素的函數:

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++;
}

我不知道它有多好/正確,但確實可以。

非常感謝您的建議和幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM