Удалить данные из узла - PullRequest
0 голосов
/ 22 марта 2012
#include <conio.h>
#include <iostream>
#include <string>

using namespace std;

class MysticalBag
{
private:
    int useCount;
    int content;
    string itemName;

public:

    MysticalBag *next_ptr;

    void setAttributes()
    {
        //Called for showing the items without any placement of item
        useCount = 1;
        content = 5;
        itemName = "Healing Potion";
    }

    int takeUseCount()
    {
        return useCount;
    }

    int takeContent()
    {
        return content;
    }

    string takeItemName()
    {
        return itemName;
    }

    void setAttributes(int userCount, int content, string itemName)
    {
        this->useCount = useCount;
        this->content = content;
        this->itemName = itemName;
    }

    void itemAdder()
    {
        cout << "Enter use count (1-3) " <<endl;
        cin >> useCount;
        cout << "Enter content (1.0 - 100.0) " <<endl;
        cin >> content;
        cout << "Enter item name as text" << endl;
        cin >> itemName;
        cout<< itemName <<" is added in the bag."<< endl;
    }

    void showBag()
    {
        cout << "Showing bag contents" << endl << endl;
        cout << itemName << endl;
        cout << "U - "<< useCount <<", C - "<< content << endl;
    }
};



int main()
{
    char choice1,choice2;
    choice1 = 0;

    MysticalBag *head, *tail, *navigator;

    navigator = new MysticalBag();
    navigator->setAttributes();
    head = navigator;
    tail = navigator;

    tail->next_ptr = NULL;

    while(choice1 !='x')
    {
        cout << "What do you want to do with the bag?" << endl;
        cout << "(a)dd item" << endl;
        cout << "(r)emove item" << endl;
        cout << "(s)how items" <<endl;
        cout << "e(x)it" <<endl;
        cin >> choice1;

        if(choice1 == 'a')
        {
            navigator = new MysticalBag();
            if(head==NULL)
            {

                head=navigator;

                tail=navigator;

                tail->next_ptr=NULL;
            }

            navigator->itemAdder();
            tail->next_ptr = navigator;
            tail = navigator;
            tail->next_ptr = NULL;
        }

        else if(choice1 == 'r')
        {
            navigator = head;
            tail = head;

            while(navigator->next_ptr != NULL)
                {
                    navigator = navigator->next_ptr;
                    tail = navigator;
                }

            cout << "Do you want to remove "<< navigator->takeItemName() <<" from your bag? (y/n)"<< endl;
            cin >> choice2;

            if(choice2 == 'y')
            {
                navigator = head;
                if(navigator == head)

                //I am stuck at this point!

                navigator = NULL;

            cout << "Item removed." << endl;

            tail = head;

            while(tail->next_ptr != NULL)
                {
                    tail = tail->next_ptr;
                }
            }
            else
            {
                cout<< "No item removed" <<endl;
            }

            navigator = head;

            if(navigator == head && navigator == tail)
            {
                navigator = NULL;
                head = NULL;
                tail = NULL;
            }
            else
            {
                navigator = tail;
                navigator = NULL;
                tail = NULL;

                tail = head;

                while(tail->next_ptr != NULL)
                {
                    tail = tail->next_ptr;
                }
            }
        }

        else if(choice1 != 'x')
        {
            navigator = head;
            while(navigator != NULL)
            {
                navigator->showBag();
                navigator = navigator->next_ptr;
            }
        }
    }
    getch();
}

Моя цель - удалить данные из узла. пользователь может ввести данные в узел, который является навигатором.

То, о чем я думаю, это навести навигатор на голову и заставить голову вызывать setAttributes (). Который покажет «Целительное зелье». Но, если пользователь добавляет в элементы. Как мне удалить только один элемент за раз?

Ответы [ 3 ]

0 голосов
/ 22 марта 2012

Это список?Почему бы вам не использовать std :: list внутри вашего пользовательского класса?

0 голосов
/ 26 июня 2013

Короче говоря, вы спрашиваете: «Как получить доступ к функции класса, если у меня есть указатель на член класса?По крайней мере, так я это вижу.

#include "Items.h" //let me assume you have some sort of struct or class for items in your bag
class Bag : public player { //player would give access to attributes like HP/MP/Who Owns the bag, etc..
    protected:
        vector<Item*> Contents; 
        int MaxItems;

    public:
        Bag();
        Store(Item* It);
        Remove(Item* It);
        UseItem(Item* It);
};
Bag::Store(Item* It) {
    if(Contents.size() >= MaxItems) return;
    for( int i = 0; i < Contents.size(); i++ ) {
        if(It == Contents[i] ) {
            return;
        }
    }
    Contents.push_back(It);
}
Bag::Remove(Item* It) { 
    for(int i = 0; i < Contents.size(); i++) {
        if( It == Contents[i] ) {
            Contents.erase(Contents.begin() + i);
            break;
    }
}        
Bag::UseItem(Item* It) {
    if(!(It->Usable())) { return };
    It->Use();
}

class Item { 
    protected:
       int ItemType; //suggest you use some enum for this
    public:
       Item();
       virtual bool Usable();
       virtual void Use();
};

Item::Item() { };
bool Item::Usable() {
    //Purely Virtual
}
void Item::Use() { 
     //Same
}

class Potion : public Item {
    protected:
       int PotionType; //Again, I'd enum this
    public: 
       Potion();
       virtual bool Useable();
       virtual void Use();
}

Potion::Potion() { ItemType = POTION; }
bool Potion::Useable() { return true; }
void Potion::Use() { //Purely Virtual }

class HealPotion : public Potion {
    protected:
        int Strength; //who knows, # of hp to heal
    public:
        HealPotion();
        virtual void Use();
};
HealPotion::HealPotion() { PotionType = Heal; Strength = 45; }
void HealPotion::Use() { Owner->ChangeHits(Strength); 
    this->RemoveItem(this); } //Now you might also want to destroy the item to free up memory
0 голосов
/ 22 марта 2012

Можно ли удалить только последний элемент, добавленный в сумку, или можно удалить любой элемент?Более общий случай - запрос на удаление из связанного списка.

Чтобы удалить узел (элемент) из связанного списка (сумка), вам необходимо знать родительский элемент элемента, который вы хотите удалить.Родителем узла является узел, который next_ptr является узлом.Итак, в цикле вам нужно отследить родителя навигатора:

while(navigator->next_ptr != NULL)
    {
        /* a sample list */
        /* "parent" --> "navigator" --> "navigator->next_ptr" */
        parent = navigator; /* now we know who points to navigator */
        navigator = navigator->next_ptr;
        tail = navigator;
    }

Как только мы узнаем родителя навигатора, все, что нужно сделать для удаления навигатора:

parent->next_ptr = navigator->next_ptr;
/* now the list looks like */
/* "parent" --> "navigator->next_ptr" */

А теперь навигатор удален из сумки.

Я думаю, что со многими из ваших циклов while все еще есть проблемы, но для их исправления требуется больше информации о ваших намерениях.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...