Search code examples
c++nodessingly-linked-list

Adding multiple data attributes to one node


I need a way to add more than one data ( such as name, id, age) into a single node in a linked list in C++. Instead of having the data value being only a name or a number.


Solution

  • I think you wish to group your data, there are many ways to do that. The easiest is if you create a stucture:

    struct MyData {
        int id;
        std::string name;
        int age;
    };
    
    MyData data;
    data.id = 1;
    data.name = "John";
    data.age = 23;
    
    std::list<MyData> list;
    list.push_back(data);
    
    ...
    
    std::list<MyData>::const_iterator itr = list.begin();
    int age = itr->age;
    

    Would that help?