Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a class with an array

I have a class like this:

class MyClass {
    MyClass(double *v, int size_of_v){
        /*do something with v*/
    };
};

My question: Is there any way, I can initialize such class without defining an array of double and feeding it to the constructor?

I would like to do something like:

auto x = MyClass({1.,2.,3.}, 3);
like image 800
Stefano Rossotti Avatar asked Feb 01 '19 00:02

Stefano Rossotti


People also ask

How do you initialize a class array in Java?

Initializing an array In order to store values in the array, we must initialize it first, the syntax of which is as follows: datatype [ ] arrayName = new datatype [size];

How do you initialize in array?

The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.

Can you initialize an array in Java?

Array Initialization in Java To use the array, we can initialize it with the new keyword, followed by the data type of our array, and rectangular brackets containing its size: int[] intArray = new int[10]; This allocates the memory for an array of size 10 . This size is immutable.

Can we initialize an array with in C++?

It can be done by specifying its type and size, initializing it or both.


1 Answers

It is called list initialization and you need a std::initilizer_list constructor, that to be achieved in your MyClass.

#include <initializer_list>  

class MyClass 
{
    double *_v;
    std::size_t _size;
public:

    MyClass(std::initializer_list<double> list) 
        :_v(nullptr), _size(list.size())
    {
        _v = new double[_size];
        std::size_t index = 0;
        for (const double element : list)
        {
            _v[index++] = element;
        }

    };

    ~MyClass() { delete _v; } // never forget, what you created using `new`
};

int main()
{
    auto x = MyClass({ 1.,2.,3. }); // now you can
    //or
    MyClass x2{ 1.,2.,3. };
    //or
    MyClass x3 = { 1.,2.,3. };
}

Also note that providing size_of_v in a constructor is redundant, as it can be acquired from std::initializer_list::size method.

And to completeness, follow rule of three/five/zero.


As an alternative, if you can use std::vector, this could be done in a much simpler way, in which no manual memory management would be required. Moreover, you can achieve the goal by less code and, no more redundant _size member.

#include <vector>
#include <initializer_list>    

class MyClass {
    std::vector<double> _v;
public:    
    MyClass(std::initializer_list<double> vec): _v(vec) {};
};
like image 120
JeJo Avatar answered Sep 23 '22 10:09

JeJo