Reputation: 395
What program does is as follows:
The list contains product information which includes product id, name, price etc.
Any hints on how to do it?
Upvotes: 0
Views: 150
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
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
Reputation: 1096
you can use multiset/multimap they have erase operation that erases all occurrences of a key
Upvotes: 1