0

程序的作用如下:

该列表包含产品信息,包括产品 ID、名称、价格等。

  1. 用户输入产品 ID
  2. 检查 id 是否已存在于列表中
  3. 因此,如果 id 与列表中的 id 匹配,它将删除该 id 的所有元素(产品 id、名称、价格等)

关于如何做的任何提示?

4

3 回答 3

1

您可以使用 multiset/multimap 它们具有擦除所有出现的键的擦除操作

于 2013-05-15T02:21:30.813 回答
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;
    }
}
于 2013-05-15T02:31:00.120 回答
0

使用擦除删除成语。假设您使用的是 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实际上从列表中删除数据。

于 2013-05-17T07:53:56.553 回答