C++ Vector initial capacity

后端 未结 2 1618
暗喜
暗喜 2020-12-20 11:46

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

2条回答
  •  悲&欢浪女
    2020-12-20 12:02

    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 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 bar;
    bar.reserve(4);
    

提交回复
热议问题