How is std::vector implemented, using what data structure? When I write
void f(int n) {
std::vector<int> v(n);
...
}
Is the vector v allocated on stack?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The
vectorobject will be allocated on the stack and will internally contain a pointer to beginning of the elements on the heap.Elements on the heap give the
vectorclass an ability to grow and shrink on demand.While having the
vectoron the stack gives the object the benefit of being destructed when going out of scope.In regards to your
[]question, thevectorclass overloads the[]operator. I would say internally it’s basically doing something like this when you doarray[1]:Where the
vectorkeeps track of the start of it’s internal heap with_Myfirst.When your
vectorstarts to fill up, it will allocate more memory for you. A common practice is to double the amount of memory needed each time.Note that
vectorinherits from_Vector_val, which contains the following members: