Reputation: 87
I was learning about classes in my C++ class, and I was trying to understand some of the things about common classes I've used. One of which being vector. I looked through the vector reference on Cplusplus.com, but there was one thing that I couldn't quite understand and was having trouble finding answers to it online. When making a new vector with predetermined values it's possible to do as follows:
vector<int> vect = {1,2,3,4,5};
cout<< vect.at(2);
What's confusing to me is that I have no idea how this works, and how to possibly replicate this in a class of my own. I've looked through the constructors of the vector class but didn't see anything that seemed to relate to instantiation in this manner. Something like vector<int> vect(6)
makes sense to me because it's just creating a vector with default size 6, but the way I mentioned above is very different from what I've seen and learned thus far.
So my questions are: How can a vector be instantiated this way, and what might a constructor for this look like?
Upvotes: 1
Views: 80
Reputation: 1373
This uses an std::initializer_list. Just like "string"
forms a string, {element1, element2, ...}
forms an initializer list that can be converted to a vector, or another datatype.
For example, we could construct an array manually doing the following:
int w[4];
auto x = {1, 2, 3, 4}; //type is std::initializer_list
int count = 0;
for(auto i : x){
w[count] = i;
count++;
}
Upvotes: 1