简体   繁体   中英

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;
}

Use a standard std::vector container instead of a raw pointer. std::vector is a wrapper for a dynamic array, and it has a constructor that accepts a std::initializer_list as input.

#include <initializer_list>
#include <iostream>
#include <vector>
using namespace std;

class vec {
private:
    vector<double> data;

public:
    vec(initializer_list<double> ilist) : data(ilist) {}
};

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM