Search code examples
c++11initializationinitializer-list

What should I do to add data/values/objects to an initializer list and later send it to a constructor?


So I wanted to practice my skills of using smart pointers. I created a template of class (one-linked list) that has constructor like:

template <class Type> 
class list
  {
          //...
   public:
          list( std::initializer_list < Type > initlist ) { ... }

          //...
    };

In main-function I want to construct initializer list and pass it to the class constructor as one thing (smth like this, I think it can be possible but I don't know how to do):

typedef int Type;

int main ()
{
   //...
   size_t count; // to know How many elements initlist will have
   std :: initializer_list < Type > initlist;

   cout << "Enter, please, count of elements and their values\n";
   cin >> count;

   Type temp_data;

   for (size_t i = 0; i < count; i++)
     {
        cin >> temp_data; //user input data and program add it to list
        initlist.push_back( temp_data ); 
 // it's wrong. But I found no analogue of "push_back" in std :: initializer_list
 // I used push_back to explain what I want to do
     }

   // ... do stuff

   // now I want to pass it to the class object
   list < Type > mylist ( initlist ); // or mylist = initlist, or mylist{initlist}

}

I could do smth like below but if I don't know how many and what elements will be input by user then what I should do:

list <Type> mylist {1,2,3,4,5,6,7,8};

So, What should I do to write it correctly? Maybe somebody has an idea. Thanks.


Solution

  • Usually in C++ containers provide both an std::initializer_list constructor and a constructor that takes two iterators (of any given size) and copies the content of that "range" into the container.

    So for example your class could have something like this:

    template <class Type> 
    class list {
        //...
    public:
        list(std::initializer_list<Type> initlist) { ... }
    
        template<typename It>
        list(It begin, It end) { ... }
    
        //...
    };
    

    In the standard library std::vector, std::liststd::forward_list, std::deque and other containers all support those.

    This is done so that if a user knows the elements he/she wants to insert into the container at the moment the container is created he/she uses the std::initializer_list overload. Otherwise if he/she has some other dynamically built container, he can just import the elements in your container.