从数组中删除元素

时间:2013-09-18 05:06:15

标签: c++

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

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;



    }}}

1 个答案:

答案 0 :(得分: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--;
        }
    }
}