什麼程序做如下:如何從C++中一次刪除多個元素?
列表包含產品信息包括產品ID,名稱,價格等
- 用戶輸入產品編號
- 檢查ID,如果它已經存在一個名單
- 因此,如果ID列表中的ID相匹配,它shud刪除ID的所有元素(產品ID,名稱,價格等)
如何做到這一點的任何提示?
什麼程序做如下:如何從C++中一次刪除多個元素?
列表包含產品信息包括產品ID,名稱,價格等
如何做到這一點的任何提示?
您應該使用結構或類存儲產品的信息,所以它會在列表中的一個元素:
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;
}
}
使用erase-remove idiom。假設你正在使用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
實際上從列表中擦除數據。
是否有必要在那裏放假? – lily
@aayat:更改了方法,因此它可以正確處理具有相同ID的多個元素。 – fbafelipe