Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Vector initial capacity

Tags:

c++

vector

I have some code which uses thousands of vectors each vector has only 4 entries, So I want to set the initial size of each vector to 4 so that I can optimize memory usage by not reserving unused memory.

I tried reserve method:

vector<Foo> bar;
bar.reserve(10);

but seems it expands and doesn't shrink, seems there also no constructor that creates a vector with a specified capacity.

Also 2 bonus questions:

What's the default initial capacity

Can I create a vector with a specific capacity?

like image 567
mmohab Avatar asked May 01 '14 18:05

mmohab


People also ask

What is the initial capacity of vector?

Default initial capacity of Vector is 10. java. util. Vector default constructor defines size of 10.

How do you calculate vector capacity?

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.

How do I set the size of a vector after initialization?

The C++ function std::vector::resize() changes the size of vector. If n is smaller than current size then extra elements are destroyed. If n is greater than current container size then new elements are inserted at the end of vector. If val is specified then new elements are initialed with val.

What is the correct way to initialize vector in C++?

Begin Declare v of vector type. Call push_back() function to insert values into vector v. Print “Vector elements:”. for (int a : v) print all the elements of variable a.


2 Answers

The capacity of a vector cannot be controlled by the constructors - there is no applicable overload.

The C++ standard doesn't give any guarantee about the capacity of a default-constructed vector vector<Foo> bar;. However all well-known implementations use 0 as the default capacity. This is something you can rely on, as allocating memory at that point just doesn't make sense.

So I believe the answer to your question is: just use

vector<Foo> bar; bar.reserve(4); 
like image 159
Alex Avatar answered Sep 21 '22 02:09

Alex


each vector has only 4 entries

Then you're probably better off with a std::array<Foo, 4> instead.

And in case you need 4 elements because you want a mathematical vector, I suggest a struct:

struct Vector
{
    Foo x, y, z, w;
};
like image 28
fredoverflow Avatar answered Sep 20 '22 02:09

fredoverflow