Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a class with an array?

With STL's vector class I can initialize a vector using a list (or array) of items:

std::vector<int> = { 1, 2, 3 };

Is it possible for me to implement this functionality into my own classes? I am writing my own Vector class for practice implementing data structures and would like to do:

MyVectorClass<int> = { 1, 2, 3 };
like image 305
Thomas Paine Avatar asked Aug 30 '26 14:08

Thomas Paine


2 Answers

Yes. Use std::initializer_list.

Define a constructor in your class that takes a std::initializer_list<T>:

MyVectorClass(std::initializer_list<T> initializer)
{
    for(T& i : initializer)
    {
        // Do whatever you want with items
    }
}
like image 99
MRB Avatar answered Sep 02 '26 05:09

MRB


Of course. It's one of the design goals of C++ that the standard library can be implemented in the language (with a few notable exceptions).

What you are looking for is called std::initializer_list. It is not an array! See std::vector constructor documentation.

like image 45
Christian Hackl Avatar answered Sep 02 '26 03:09

Christian Hackl