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 };
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
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With