Как создать уникальный идентификатор в связанном списке? - PullRequest
0 голосов
/ 10 мая 2018

В настоящее время я изучаю, как использовать связанный список в классе в свободное время. Теперь я знаю только, как вставить, отобразить и удалить. Я могу удалить, используя int age;, но я думаю, что было бы лучше, если бы я мог сгенерировать уникальный идентификатор, который будет легче запомнить (удобный для пользователя), для всех данных в связанном списке, чтобы я мог удалить по его идентификатору.

Я хочу знать, есть ли возможность для меня создать уникальный идентификатор в функции getInput();?

Если да, пожалуйста, дайте мне подсказку, как это сделать. Спасибо!

struct list
{
    list *head, *tail;
    list *next;
}
class node
{
    private:
        std::string name; // Name
        int age; // Age in integer
        float height; // In meters

    public:
        node *next; // Pointer to next node
        node *head, *tail;
        node *start_ptr = NULL; // Start Pointer (root)
        node *temp;
        node *temp2;
        node *pNextValue;
        node* prev; // empty header
        node* current;
        void printList();
        void delete_end_node();
        void search();
        void sort_age();
        void deletebyAge();
    node()
        {
            head = NULL;
            tail = NULL;
        }


        void getInput()
        {
            temp = new node;
            cout << "ID: ";
            // This is where I want to generate unique ID
            cout << "Name: ";
            cin >> temp->name;
            cout << "Age: ";
            cin >> temp->age;
            cout << "Height: ";
            cin >> temp->height;

            cout<<"\n";
            temp->next = NULL; // Sets the node to be the last node
            if (start_ptr == NULL)
                start_ptr = temp;
            else
            {
                temp2 = start_ptr; // We know temp2 is not NULL - list not empty!
                while (temp2->next != NULL) // The loop will terminate when temp2
                    temp2 = temp2->next; // points to the last node in the list
                // Move to next link in chain
                temp2->next = temp; // Sets the pointer from that last node to point to the node that has just declared
            }
        } // End of getInput() function
}; //End of class

1 Ответ

0 голосов
/ 10 мая 2018

В C ++ личность объекта является его адресом. Вы можете использовать node адрес в качестве его идентификатора, например ::100100

class node
{
    private:
        std::string name; // Name
        int age; // Age in integer
        float height; // In meters

    friend std::ostream& operator<<(std::ostream& s, node& n) {
        return s << "id:" << &n
                 << ' ' << "name:" << n.name
                 << ' ' << "age:" << n.age
                 << ' ' << "height:" << n.height
                 << '\n';
    }
    // the rest of your code...
};

А затем распечатайте это как:

node n;
std::cout << n;

В качестве альтернативы используйте серийный счетчик:

class node
{
private:
    std::string name; // Name
    int age; // Age in integer
    float height; // In meters
    unsigned const id;

    static unsigned object_counter;

public:
    node()
        : id(++object_counter)
    {}

    friend std::ostream& operator<<(std::ostream& s, node& n) {
        return s << "id:" << n.id
                 << ' ' << "name:" << n.name
                 << ' ' << "age:" << n.age
                 << ' ' << "height:" << n.height
                 << '\n';
    }
    // the rest of your code...
};

unsigned node::object_counter = 0;
...