2013-05-15 36 views
0

什麼程序做如下:如何從C++中一次刪除多個元素?

列表包含產品信息包括產品ID,名稱,價格等

  1. 用戶輸入產品編號
  2. 檢查ID,如果它已經存在一個名單
  3. 因此,如果ID列表中的ID相匹配,它shud刪除ID的所有元素(產品ID,名稱,價格等)

如何做到這一點的任何提示?

回答

1

您應該使用結構或類存儲產品的信息,所以它會在列表中的一個元素:

struct Product { 
    unsigned int id; 
    std::string name; 
    float price; // you could also use int and represent the cents 
}; 

typedef std::list<Product> ProductList; 


void removeProduct(ProductList & productList, unsigned int id) { 
    ProductList::iterator it = productList.begin(); 
    while (it != productList.end()) { 
     if (it->id == id) { 
      it = productList.erase(it); 
     } 
     else ++it; 
    } 
} 
+0

是否有必要在那裏放假? – lily

+0

@aayat:更改了方法,因此它可以正確處理具有相同ID的多個元素。 – fbafelipe

1

可以使用多集/多重映射 他們erase operation是刪除所有出現的一個關鍵

+0

有沒有辦法做到這一點與列表? – lily

+0

你可以通過列表並查找該ID – Sergi0

0

使用erase-remove idiom。假設你正在使用C++ 11 lambda表達式,這很容易。

#include <vector> 
#include <algorithm> 
class Product 
{ 
public: 
    unsigned int id; 

}; 

void deleteProduct(std::vector<Product>& products, unsigned int productId) 
{ 
    products.erase(std::remove_if(products.begin(), products.end(), 
     [&productId] (const Product& product) 
    { 
     return product.id == productId; 
    }), products.end()); 
} 

remove_if算法將匹配的元素移動到列表的末尾。然後它將一個迭代器返回到可以被擦除的第一個元素。然後erase實際上從列表中擦除數據。

相關問題