Domanda

When using a linked list that stores numerous objects how would you go about access the data inside said object?.

Example code.

using namespace std;

typedef struct node                                                
{                                                               
  int data;               
  node* next;             
} *nodePtr;

nodePtr head;
nodePtr current;
nodePtr temp;

void PrintList()
{
    current = head;
    while(current != NULL)
    {
        cout << current->data.getMakeModel();
        cout << current->data.getRegNo();
        cout << current->data.getEngineSize();
        cout << current->data.getRented();

        current=current->next;
    }
}

My current way of doing it doesn't work and I'm not sure how to solve it.

All i need to do is access the template object data members which i have getter methods for and output the data.

Any ideas?

On a side note, would it be possible to search for a specific object(an object with specific data member value) in a linked list? with the objects still using templates of course

È stato utile?

Soluzione

When using a linked list that stores numerous objects how would you go about access the data inside said object?

If you have a nodePtr you'll have to do ptr->data to access the int of the struct.


My current way of doing it doesn't work and I'm not sure how to solve it.

You are trying to access member functions on an object of type int, that does not have any. You probably meant to define another type for the data member object of node.


On a side note, would it be possible to search for a specific object(an object with specific data member value) in a linked list?

Of course, the implementation of such an algorithm is pretty trivial. You can implement it along the lines of:

nodePtr find(nodePtr head, int value) {
    for (; head != NULL; head = head->next)
        if (*head == value)
            return first;
    return NULL;
}

What I would suggest is to use the standard std::forward_list or std::list. If you do, you'll be able to use std::find for the "find"-algorithm.

Altri suggerimenti

The probem here is that data is of type int and not of a class type. You will have to change its type to a class type e.g Foo. A more advanced solution will use templates to make it work with arbitrary types (e.g std::list)


Also notice that your class definition is not considered good style. I would define it as:

struct node                                                
{   
    typedef node* Ptr;

    Foo data;               
    node* next;             
};

While the typedef is only reasonable in some special cases (e.g if working extensively with smart pointers and reference counting). In normal cases one should go with node* (which is also smaller o.O)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top