Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i construct a linked list with curly braces?

I am fairly new to object oriented C++, and I'm trying to make a constructor for a linked list in this way:

Somewhere in the List.h we'd have this:

struct Node
{   
    int data;
    Node *next;
}; 

and then in the main.cpp, I'd like to be able to construct a list like this:

int main()
{
List A({1,2,3,4,5,6});// I want the amount of numbers to indicate the size of
 //the list and the numbers to go into each node in order
return 0;    
}

So my question is, can i make such a constructor? If so then how? Do i have to use templates do this? I tried to find a question like this answered in SO but they all included templates and i haven't learned that yet. If i can make my constructor to do this, is it possible to do it without using templates?

like image 460
cpp user Avatar asked Nov 01 '22 02:11

cpp user


1 Answers

Yes you can do this (using C++11).

You need to define a constructor taking an std::initializer_list<int>. (Yes this is a template, but I will show you how to use it. :-) )

A possible implementation of an std::intitializer_list<int>-constructor could look like this:

//in class List:
List (std::initializer_list<int> init) {
    for (auto v : init)
        this->emplace_back(v);
}

where you have to implement emplace_back yourself as an exercise. emplace_back should construct a new Node and append it to the List. It will be a useful member function (I promise).

Probably unimportant notice: If emplace_back does heap allocations, this code might leak. In this case, delegate to a constructor that puts the List into a valid state, so the destructor can free all the heap-allocated Nodes. If you do not understand this, it is most likely not too important for your application.

like image 100
Baum mit Augen Avatar answered Nov 09 '22 06:11

Baum mit Augen