lily
lily

Reputation: 395

How to delete several elements from list at once in c++?

What program does is as follows:

The list contains product information which includes product id, name, price etc.

  1. User enters product id
  2. Check the id if it already exist in a list
  3. So if the id matches the id in the list, it shud delete all the elements of that id (product id,name,price etc)

Any hints on how to do it?

Upvotes: 0

Views: 150

Answers (3)

Steve
Steve

Reputation: 7271

Use the erase-remove idiom. Assuming you're using C++11 lambdas make this easy.

#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() );
}

The remove_if algorithm moves the elements that match to the end of the list. It then returns an iterator to the first element that can be erased. The erase then actually erases the data from the list.

Upvotes: 0

fbafelipe
fbafelipe

Reputation: 4952

You should use a struct or class to store the product information, so it will be in a single element of the list:

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;
    }
}

Upvotes: 1

Sergi0
Sergi0

Reputation: 1096

you can use multiset/multimap they have erase operation that erases all occurrences of a key

Upvotes: 1

Related Questions