Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
List 如何在c+中一次从列表中删除多个元素+;?_List_Stl - Fatal编程技术网

List 如何在c+中一次从列表中删除多个元素+;?

List 如何在c+中一次从列表中删除多个元素+;?,list,stl,List,Stl,程序的作用如下: 该列表包含产品信息,包括产品id、名称、价格等 用户输入产品id 检查该id是否已存在于列表中 因此,如果id与列表中的id匹配,它应该删除该id的所有元素(产品id、名称、价格等) 有关于如何操作的提示吗?您可以使用multiset/multimap 它们具有删除所有出现的键的功能您应该使用结构或类来存储产品信息,因此它将位于列表的单个元素中: struct Product { unsigned int id; std::string name; fl

程序的作用如下:

该列表包含产品信息,包括产品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;
        }
    }
    
    struct产品{
    无符号整数id;
    std::字符串名;
    float price;//还可以使用int并表示美分
    };
    typedef std::list ProductList;
    void removeProduct(ProductList&ProductList,未签名的整数id){
    ProductList::iterator it=ProductList.begin();
    while(it!=productList.end()){
    如果(it->id==id){
    它=productList.erase(它);
    }
    否则它;
    }
    }
    
    使用。假设您使用的是C++11 lambdas,那么这就很容易了

    #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() );
    }
    
    #包括
    #包括
    类产品
    {
    公众:
    无符号整数id;
    };
    void deleteProduct(std::vector&products,unsigned int-productId)
    {
    products.erase(std::remove_if(products.begin(),products.end(),
    [&productId](常量产品和产品)
    {
    return product.id==productId;
    }),products.end());
    }
    

    remove\u if
    算法将匹配的元素移动到列表的末尾。然后它返回一个迭代器到第一个可以擦除的元素。
    erase
    实际上会从列表中删除数据。

    是否有办法使用列表执行此操作?您可以浏览列表并查找id,我是否需要将断点放在那里?@aayat:更改了方法,因此它可以正确处理具有相同id的多个元素。