3

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 };
1
  • 2
    Look at std::initializer_list<int>. Commented Jan 22, 2017 at 17:31

2 Answers 2

5

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

3

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.

1 Comment

It might be worth giving an example of these exceptions, or linking to a list.

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.