程序的作用如下:
该列表包含产品信息,包括产品 ID、名称、价格等。
- 用户输入产品 ID
- 检查 id 是否已存在于列表中
- 因此,如果 id 与列表中的 id 匹配,它将删除该 id 的所有元素(产品 id、名称、价格等)
关于如何做的任何提示?
您可以使用 multiset/multimap 它们具有擦除所有出现的键的擦除操作
您应该使用结构或类来存储产品信息,因此它将位于列表的单个元素中:
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;
}
}
使用擦除删除成语。假设您使用的是 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
实际上从列表中删除数据。