0

プログラムは次のようになります。

リストには、製品 ID、名前、価格などを含む製品情報が含まれています。

  1. ユーザーが製品 ID を入力
  2. リストにすでに存在する場合はIDを確認してください
  3. そのため、ID がリスト内の ID と一致する場合、その ID のすべての要素 (製品 ID、名前、価格など) を削除します。

それを行う方法に関するヒントはありますか?

4

3 に答える 3

1

製品情報を格納するには構造体またはクラスを使用する必要があるため、リストの単一の要素になります。

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;
    }
}
于 2013-05-15T02:31:00.120 に答える
1

マルチセット/マルチマップを使用できます。キーのすべての出現を消去する消去操作があります

于 2013-05-15T02:21:30.813 に答える
0

消去削除イディオムを使用します。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、実際にリストからデータを消去します。

于 2013-05-17T07:53:56.553 に答える