Initializing the Size of a C++ Vector
What Are the Advantages (If Any) of Initializing the Size of a C++ Vector as Well as Other Containers? Is There Any Reason to Not Just Use the Default No-Arg...
What are the advantages (if any) of initializing the size of a C++ vector as well as other containers? Is there any reason to not just use the default no-arg constructor?
Basically, are there any significant performance differences between
vector<Entry> phone_book;
and
vector<Entry> phone_book(1000);
These examples come from The C++ Programming Language Third Edition by Bjarne Stroustrup. If these containers should always be initialized with a size, is there a good way to determine what a good size to start off would be?
4 Answers
There are a few ways of creating a vector with n elements and I will even show some ways of populating a vector when you don't know the number of elements in advance.
Must Read
But first
what NOT to do
std::vector<Entry> phone_book;
for (std::size_t i = 0; i < n; ++i)
{
phone_book[i] = entry; // <-- !! Undefined Behaviour !!
}
The default constructed vector, as in the example above creates an empty vector. Accessing elements outside of the range of the vector is Undefined Behavior. And don't expect to get a nice exception. Undefined behavior means anything can happen: the program might crash or might seem to work or might work in a wonky way. Please note that using reserve doesn't change the actual size of the vector, i.e. you can't access elements outside of the size of the vector, even if you reserved for them.