Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector of vectors, reserve

Tags:

c++

stdvector

Suppose I want to represent a two-dimensional matrix of int as a vector of vectors:

std::vector<std::vector<int> > myVec; 

The inner dimension is constant, say 5, and the outer dimension is less than or equal to N. To minimize reallocations I would like to reserve space:

myVec.reserve(N); 

What size is assumed for the inner vector? Is this purely implementation dependent? How does this effect the spatial locality of the data? Since the inner dimension is a constant is there a way to tell the compiler to use this constant size? How do these answers change if the inner vector's size changes?

like image 619
OSE Avatar asked Sep 24 '13 20:09

OSE


People also ask

What is vector Reserve?

std::vector::reserveRequests that the vector capacity be at least enough to contain n elements. If n is greater than the current vector capacity, the function causes the container to reallocate its storage increasing its capacity to n (or greater).

Does vector insert reserve?

If the allocated memory capacity in the vector is large enough to contain the new elements, no additional allocations for the vector are needed. So no, then it won't reserve memory.

How do you reserve the size of a vector?

C++ Vector Library - reserve() FunctionThe C++ function std::vector::reserve() requests to reserve vector capacity be at least enough to contain n elements. Reallocation happens if there is need of more space.


1 Answers

Since your inner dimension is constant, I think you want

std::vector< std::array<int, 5> > vecs; vecs.reserve(N); 

This will give you preallocated contiguous storage, which is optimal for performance.

like image 113
Ben Voigt Avatar answered Oct 08 '22 19:10

Ben Voigt