Search code examples
c++c++11initializer-list

How to initialize dynamic array in constructor using initializer_ist?


I am trying to initialize the dynamic array in the constructor using initialize_list in C++. How can I achieve this?

#include <cstdlib> 
#include <initializer_list>
#include <iostream>
#include <utility>

using namespace std;

class vec {
private:
    // Variable to store the number of elements contained in this vec.
    size_t elements;
    // Pointer to store the address of the dynamically allocated memory.
    double *data;

public:
    /*
      * Constructor to create a vec variable with the contents of 'ilist'.
    */
    vec(initializer_list<double> ilist);
}

int main() {
    vec x = { 1, 2, 3 };  // should call to the constructor 
    return 0;
}

Solution

  • initializer_list has size method, it gives you information how many elements must be allocated by new, so it could be:

    vec(initializer_list<double> ilist)
    {
        elements = ilist.size();
        data = new double[ ilist.size() ];
        std::copy(ilist.begin(),ilist.end(),data);
    }