if we write a[100] this means 100 points in memory has been allocated to array a … when we write v.reserve(100) this also reserves the memory so what is the difference between them??
Vector memory allocation
-
If we make an array of size 100, then we can only add 100 elements at most to it.
-
When a vector is created, it is made of a fixed length, let’s say n. If add the one more element after adding n elements then the size of the vector will automatically increase to 2n, and after adding 2n elements the size of the vector will automatically to 4n. Doubling the size of a vector is a very time-consuming step.
-
Now let’s assume we know that we are going to enter 100 elements. And we create a vector ‘v’ normally without reserving any size. The vector created will be of size less than 100, so after adding certain elements the size of the vector will double and that will take a lot of time internally. So we use the reserve function.
-
Reserve function will create the vector of the size that we enter. Initially creating a vector of size 100 is a better option than creating a vector of smaller size and gradually doubling the size of if to reach 100.
Hope this helps.