Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: std::vector::reserve not reserving when containing pointers

Tags:

When I call std::vector::reserve when the identifier is of type std::vector<Foo*> reserve(...) does nothing:

std::vector<int*> bar;
bar.reserve(20);

//I expect bar.size to return 20...
std::size_t sz = bar.size();
for(std::size_t i = 0; i < sz; ++i) {
    //Do Stuff to all items!
}

The aforementioned for loop runs exactly zero times and bar.size() returns zero. I do not remember if this is also true for all other STL containers, but if so, including the behavior for std::vector: WHY?

like image 455
Casey Avatar asked Apr 03 '12 00:04

Casey


1 Answers

.reserve() doesn't change the size of a vector. The member function you are looking for is .resize(). reserve() is simply an optimization. If you are going to add a bunch of things to a vector one-by-one using push_back() then telling it how many you will add using reserve() can make the code run a little bit faster. But just calling reserve() doesn't change the size.

like image 52
Davis King Avatar answered Oct 14 '22 05:10

Davis King