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.
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.
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.
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));
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With