Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

size vs capacity of a vector?

Tags:

c++

vector

I am a bit confused about this both of these look same to me. Although it may happen that capacity and size may differ on different compilers. how it may differ. Its also said that if we are out of memory the capacity changes.

All these things are bit unclear to me.

Can somebody give an explanation.(if possible with and example or if I can do any test on any program to understand it)

like image 274
munish Avatar asked Jun 09 '11 17:06

munish


People also ask

What is size and capacity of vector in C++?

The size of a vector is the number of elements that it contains, which is directly controlled by how many elements you put into the vector. Capacity is the amount of total space that the vector has. Under the hood, a vector just uses an array. The capacity of the vector is the size of that array.

How do you set the capacity of a vector?

The theoretical limit on the size of a vector is given by member max_size. The capacity of a vector can be explicitly altered by calling member vector::reserve.

What is a vector size?

The vector length (or magnitude) is the length of its arrow and corresponds to the distance between initial point and terminal point. For determining the length of the arrow (and thus the magnitude of the vector), think of the following triangle.

What do you call the size of a vector?

size_type size() const noexcept; Return size. Returns the number of elements in the vector. This is the number of actual objects held in the vector, which is not necessarily equal to its storage capacity.


1 Answers

Size is not allowed to differ between multiple compilers. The size of a vector is the number of elements that it contains, which is directly controlled by how many elements you put into the vector.

Capacity is the amount of total space that the vector has. Under the hood, a vector just uses an array. The capacity of the vector is the size of that array. This is always equal to or larger than the size. The difference between them is the number of elements that you can add to the vector before the array under the hood needs to be reallocated.

You should almost never care about the capacity. It exists to let people with very specific performance and memory constraints do exactly what they want.

like image 159
John Calsbeek Avatar answered Sep 21 '22 21:09

John Calsbeek