Aniket Chowdhury
Aniket Chowdhury

Reputation: 343

How would I use initializer list to directy create my linked list?

I wrote a templated linked list under the name space mylib.

Now what I would like to do is this:

mylib::list<int> x = {2,3,4,5}

what I would like to do is create a constructor or overload assignment operator to do write above code. I read here Initializer list for dynamic array and overloading assignment operators

I cannot possibly think a way of how to this.

Upvotes: 2

Views: 1093

Answers (1)

JeJo
JeJo

Reputation: 32847

what I would like to do is create a constructor or overload assignment operator to do this. ?

You can achieve it by creating a std::initializer_list constructor.

list(std::initializer_list<int> arr)  // initializer list constructor
{
   for(const auto& it: arr) 
       head.insertElement(it);
}

where insertElement() is the method you defined to insert elements into your list class.

See a LIVE DEMO

Upvotes: 5

Related Questions