什么程序做如下:如何从C++中一次删除多个元素?
列表包含产品信息包括产品ID,名称,价格等
- 用户输入产品编号
- 检查ID,如果它已经存在一个名单
- 因此,如果ID列表中的ID相匹配,它shud删除ID的所有元素(产品ID,名称,价格等)
如何做到这一点的任何提示?
什么程序做如下:如何从C++中一次删除多个元素?
列表包含产品信息包括产品ID,名称,价格等
如何做到这一点的任何提示?
您应该使用结构或类存储产品的信息,所以它会在列表中的一个元素:
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;
}
}
使用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
实际上从列表中擦除数据。
是否有必要在那里放假? – lily
@aayat:更改了方法,因此它可以正确处理具有相同ID的多个元素。 – fbafelipe