Mastery 23

Creation and use of vectors in C++

Vector

 

Vectors are sequence containers representing arrays that can change in size.

Just like arrays, vectors use contiguous storage locations for their elements, which means that their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled automatically by the container.

Internally, vectors use a dynamically allocated array to store their elements. This array may need to be reallocated in order to grow in size when new elements are inserted, which implies allocating a new array and moving all elements to it. This is a relatively expensive task in terms of processing time, and thus, vectors do not reallocate each time an element is added to the container.

Example

Output:

Credits:

http://www.cplusplus.com/reference/vector/vector/vector/

http://www.cplusplus.com/reference/vector/vector/

1017 23

CC BY 4.0 Mastery 23 by Mauricio Cooper is licensed under a Creative Commons Attribution 4.0 International License.

Comments are closed.