プログラムは次のようになります。
リストには、製品 ID、名前、価格などを含む製品情報が含まれています。
- ユーザーが製品 ID を入力
- リストにすでに存在する場合はIDを確認してください
- そのため、ID がリスト内の ID と一致する場合、その ID のすべての要素 (製品 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;
}
}
マルチセット/マルチマップを使用できます。キーのすべての出現を消去する消去操作があります
消去削除イディオムを使用します。C++11 ラムダを使用していると仮定すると、これが簡単になります。
#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
、実際にリストからデータを消去します。