Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating a vector with known number of elements: specify its size in constructor or by using reserve method?

Tags:

c++

std

vector

I would like to create a vector of some complex type, by reading individual elements from a stream. I know the vector size in advance. Is it better to specify the number of elements in the vector constructor or by using reserve method? Which one of these two is better?

int myElementCount = stream.ReadInt();
vector<MyElement> myVector(myElementCount);
for (int i = 0; i < myElementCount; i++)
{
    myVector[i] = stream.ReadMyElement();
}

or

int myElementCount = stream.ReadInt();
vector<MyElement> myVector;
myVector.reserve(myElementCount);
for (int i = 0; i < myElementCount; i++)
{
    myVector.push_back(stream.ReadMyElement());
}

What about the case where I just create a vector of ints or some other simple type.

like image 867
mk33 Avatar asked Nov 12 '15 00:11

mk33


People also ask

How do you reserve the size of a vector?

std::vector class provides a useful function reserve which helps user specify the minimum size of the vector.It indicates that the vector is created such that it can store at least the number of the specified elements without having to reallocate memory. Each vector object has two parameters–size and capacity.

How do you initialize a vector with a specific size?

Another way to initialize a vector in C++ is to pass an array of elements to the vector class constructor. The array elements will be inserted into the vector in the same order, and the size of the vector will be adjusted automatically. You pass the array of elements to the vector at the time of initialization.

How do you declare a vector of a certain size in C++?

To initialize a two-dimensional vector to be of a certain size, you can first initialize a one-dimensional vector and then use this to initialize the two-dimensional one: vector<int> v(5); vector<vector<int> > v2(8,v); or you can do it in one line: vector<vector<int> > v2(8, vector<int>(5));

How does std::vector allocate memory?

std::vector typically allocates memory on the heap (unless you override this behavior with your own allocator). The std::vector class abstracts memory management, as it grows and shrinks automatically if elements are added or removed.


1 Answers

It depends on what MyElement is, especially what its operator= does, so it's largely the usual "try both and use the faster one for you". There is a third choice, use c++11 and emplace_back, especially if MyElement is heavy.

As a datapoint, for int or double I found that using the constructor (or resize()) and [] is faster. Specifically, this way the loop is much easier for the compiler to vectorize.

like image 187
Adam Avatar answered Nov 07 '22 04:11

Adam