0

I'm creating a custom vector class for a school project and I'd like to be able to initialize it like this:

vector x = { 2, 3, 4, 5 };

Is there any way to do this is C++?

Here is the header of my class:

class vector {
private:

    int vsize;
    int valloc;
    double* values;

public:

    vector() : vsize(0), valloc(0), values(nullptr) {}
    vector(???);
    vector(const vector& v);
    int size() const { return vsize; };
    int alloc() const { return valloc; };
    void resize(int newsize);
    void insert(double x);
    void insert(double x, int index);
    double* value() const { return values; };
    double value(int index) const { return *(values + index - 1); }

};
1
  • Use std::initializer_list. Commented Oct 25, 2019 at 19:00

1 Answer 1

3

You can support that by adding a constructor that takes a std::initialzer_list<double>.

vector(std::initializer_list<double> init) : vsize(init.size()),
                                             valloc(init.size()),
                                             values(new double[init.size()])
{
   std::copy(init.begin(), init.end(), values);
}

You can make that a bit more flexible by using a template.

template <typename T>
vector(std::initializer_list<T> init) : vsize(init.size()),
                                        valloc(init.size()),
                                        values(new double[init.size()])
{
   std::copy(init.begin(), init.end(), values);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.