Lets say i have vector of vectors
vector< vector<int> > bigTable;
bigTable.reserve(5);
To clarify my understanding of resize and reserve.
When you use push_back with vectors, you have to allocate memory each time you use it. So my goal is to set a side a set of memory space so that it will be least expensive.
As such, will reserve help with the above goal?
You don't have to allocate memory each time you call push_back. The vector starts off with a given capacity, and it only allocates extra capacity when the original capacity runs out, typically by doubling the previous capacity. You should only reserve if you are sure you are going to need the extra capacity. And you can check how much capacity you start off with using the capacity member. So, yes, a call to reserve can help, but only if you know from the outset that you really need the extra capacity. But you can also trust the vector to increase its capacity if and when it needs it.
On my particular platform, when I initialize a vector with 5 Foo elements, it has capacity 5. As I add a new element, the capacity jumps to 10. This is not mandated by the standard, the original capacity could have been much more than 5.
struct Foo {
long long n;
};
int main() {
std::vector<Foo> f(5);
std::cout << f.capacity() << "\n";
f.push_back(Foo());
std::cout << f.capacity() << "\n";
}
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