2013-05-15 35 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实际上从列表中擦除数据。

相关问题