1

ショッピング カートの内容を表すために使用する正しいデータ構造は何ですか?

  1. リンクされたリスト
  2. 配列
  3. 配列リスト
  4. 他の何か

最も便利なもの、つまり配列を使用するという観点からは考えていませんが、最も正しいものに関してはもっと考えています。

これは、次のものを含むショッピング カートの非常に標準的なアイデアです。

  1. 小計などのカートに関する基本的なメタデータ
  2. 数量や価格などのカート情報のプロパティと、基本となる製品へのアクセスを含む製品プロパティを含むカート項目のコレクション

また、次のことも重要です。

  1. アイテムは追加および削除できる必要があります
  2. カートは 1 回の操作で空にできる必要があります
  3. 小計、数量など、アイテムが追加/削除されたときに、メタデータの特定の部分を更新する必要があります。
4

2 に答える 2

3
  • 配列: ショッピング カートに入るアイテムの数を事前に知る必要があり、配列のサイズ変更/再初期化を何度も行う必要があるため、実際にはこれを行いません。
  • LinkedList (実装で Array を使用しない) : 私は主にこれを使用します。特に、あなたが言及した残りの要件に適合します。
  • ハッシュされたコレクション: 使用できますが、特定のキー要素によるバスケットの内容への高速アクセスが必要ないという事実を考えると、この状況にはあまり適していません。

要するに、ほとんどの開発者が注文アイテムのリストを使用して注文するように、ショッピング カートをモデル化するだけです。したがって、アイテムの総数、合計価格などのゲッターを使用してショッピング カート クラスを作成し、リンクされたリストを使用したコンテンツ。

もちろん、それが要因である場合は分布を検討することもできますが、ほとんどの場合、上記で十分です。

于 2013-08-08T00:06:05.267 に答える
-1

ショッピングカートの基本CPPプログラム

#include <iostream>
#include <vector>
#include <cstring>
using namespace std;

struct Item {
    string name;
    int quantity;
    int price;
};

class ShoppingCart {
private:
    vector<Item> item;
    int total_price;
public:
    ShoppingCart();
    void addItem(string name, int quantity, int price);
    void removeItem(string name, int quantity);
    int getTotal();
};

ShoppingCart::ShoppingCart() {
    cout << "Creating a new shopping cart" << endl;
    total_price = 0;
}

void ShoppingCart::addItem(string name, int quantity, int price) {
    for (int i = 0; i < item.size(); i++) {
        if (item[i].name == name) {
            item[i].quantity += quantity;
            return;
        }
    }

    Item temp;
    temp.name = name;
    temp.quantity = quantity;
    temp.price = price;
    item.push_back(temp);
}

void ShoppingCart::removeItem(string name, int quantity) {
    for (int i = 0; i < item.size(); i++) {
        if (item[i].name == name) {
            if (item[i].quantity >= quantity) {
                item[i].quantity -= quantity;
                return;
            }
            cout << "Not enough items present in the cart to be removed" << endl;
            return;
        }
    }
    cout << "This item is not present in the cart" << endl;
}

int ShoppingCart::getTotal() {
    total_price = 0;
    for (int i = 0; i < item.size(); i++) {
        total_price += item[i].quantity * item[i].price;
    }
    return total_price;
}

int main() {
    ShoppingCart cart;
    cart.addItem("Maggi", 10, 5);
    cart.addItem("Biryani", 2, 15);
    cart.addItem("Ketchup", 1, 5);
    cout << "Total cost: " << cart.getTotal() << endl;
    cart.addItem("Football", 2, 15);
    cart.removeItem("Maggi", 4);
    cart.removeItem("Ketchup", 2);
    cout << cart.getTotal() << endl;
    cart.addItem("Candy", 15, 2);
    cart.removeItem("Bat", 1);
    cout << "Total cost: " << cart.getTotal() << endl;
}
于 2016-10-14T17:47:30.523 に答える