-4

我希望能够从使用输入的库存中移除一个项目,即移除头盔,然后从阵列中移除头盔。我有一个例子,但我不知道我的哪个变量去了哪里

void remData(const InventoryRecord list[], int size) {
    system("cls");
    cout <<"Enter Item you wish to remove from your inventory: " << endl;// This is being displayed so user can see items in the inventory
    double cost = 0;

  if(size < 1) {
    cout << "Nothing to display" << endl;
  } else {
    cout << "All Items in your Bag" << endl << endl;
    cout << fixed << setprecision(2);   
    cout << "Item Name              Qty     Value" << endl;// It is not displaying right the alignment is off
    cout << "~~~~~~~~~~~~~~~~~~" << endl;
    /* from here I do not know what to do! What I want is have use type the item name they want removed
                            also display an error if they enter an  item wrong*/
    cout << left;     
    for (int i = 0; i < size; i++) {
      cout << setw(21) << list[i].name << right
           << setw(4)  << list[i].qty
           << setw(10) << list[i].value << left << endl;
           cost = cost + list[i].value * list[i].qty;


    cout << "~~~~~~~~~~~~~~~~~~~" << endl;
    cout << right << setw(3) << size;
    cout << " items listed";
    cout << right << setw(19) << cost << endl << endl;



    }}}
4

1 回答 1

1

像这样的东西可以工作,但我建议使用 std::list 因为删除可以在恒定时间内完成。如果您想保留顺序(就像我一样),只能在线性时间内完成删除数组。另一种选择是将空白位置与数组中 size-1 位置的元素交换,然后从 size 中减去 1。

注意:你必须改变你的函数头,如果你想修改它, list[] 不能是 const 并且因为你要删除元素大小应该是通过引用传递的,所以它可以被改变。

void remData(InventoryRecord list[], int &size) {
    system("cls");
    cout <<"Enter Item you wish to remove from your inventory: " << endl;// This is being displayed so user can see items in the inventory

    // the name we query for
    string qname;
    bool found = false;
    int index;

    if(size < 1) {
        cout << "Nothing to display" << endl;
    } else {
        // display the inventory for reference
        dispData(list, size);

        // prompt for name
        cout << "Name      : ";
        getline(cin, qname);
        for ( int i = 0; i < size; ++i )
            if ( qname == list[i].name )
            {
                found = true;
                index = i;
                // assuming only removing first item with this name
                break;
            }

        if (!found) {
            // you could re-prompt using a loop instead of just ending here
            cout << "Could not find item " << qname << "!" << endl;
        } else {
            // remove item from list and shift other items over the one we want to remove
            for ( int i = index; i < size-1; ++i )
            {
                // modifying list (this is why it can't be const)
                list[i].name = list[i+1].name;
                list[i].qty = list[i+1].qty;
                list[i].value = list[i+1].value;
            }
            // decrement the size (this is why it was pass-by-reference)
            size--;
        }
    }
}
于 2013-09-18T05:41:39.583 回答