39

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?

14
  • 3
    If you want it at 4, why didn't you set it at 4? Commented May 1, 2014 at 18:44
  • 4
    if you want it to shrink, use shrink_to_fit() Commented May 1, 2014 at 18:46
  • 4
    Am I the only one around here who doesn't understand what's wrong with vector<Foo> bar; bar.reserve(4);? Commented May 1, 2014 at 18:53
  • 3
    @mmohab: If that's what you need, then your question is certainly not worded to indicate it. If you want to shrink the vector's capacity, why are you talking about initializing it? Commented May 1, 2014 at 19:03
  • 1
    Come to think of it, the question would make a lot of sense if you consider the possibility than the initial capacity of a vector is more than 4 by default. So let me just say that although there is no guarantee, all well-known implementations of the standard library use 0 as the initial capacity and you can use vector<Foo> bar; bar.reserve(4); safely. Commented May 1, 2014 at 19:45

2 Answers 2

59

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);
Sign up to request clarification or add additional context in comments.

Comments

19

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;
};

4 Comments

In other words, you need a C++11 compiler. Use GCC 4.9 if you don't have it.
actually that it not what i need, the vector size may change to other value 5 for example, but all the lists have the same size
So why did you say that each has four entries? Now you're saying that they start with zero and can go over four?
@mmohab: Do you know this length at compile time?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.