std::vector

The std::vector is one of the must useful containers of the standard library. It stores an array of elements on the free store (the heap) one after the other, just like you would get if you allocated the memory using new[]. The std::vector is very handy since it is very versatile and easy to use. Being a part of the standard library it will also manage its memory for you (using RAII) which avoids the memory leak problem. Since the objects are allocated contiguously in memory is this possible to use in combination with old code which expects an array of elements.

Creating

std::vector is always allocated on the stack. It can be allocated using uniform initialization:

or using just the size:

It is possible to add elements to the vector one at a time using push_back;

however, pushing back elements at the end of the vector is not recommended if the vector should hold hundreds of elements or more. When you push_back an element to the end then the underlying array will occasionally be resized by allocating a new array and copying all the elements from the old to the new array and this is a very time consuming process.

Iterating

You can iterate through each of the values in the vector using the new range-based for (C++11):

or using std::for_each and a lambda

Number of Elements

Unlike a dynamically allocated array (allocated using new[]), you don’t have to keep track of the size of the vector. Get the number of elements in the vector by calling the method size()

See also: Converting std::vector to C array and back

Facebookgoogle_pluslinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *