What's std::vector::reserve() for?

Hello all, just wondering.

I know I should use resize() if I'm going to assign new values with the subscript operator, but what purpose does reserve() have if push_back() reserves space automatically?

Thanks.
Resize will add more new elements to the vector and makes the size bigger. Reserve will make the size bigger. If you know exactly how much you're going to use, it's best to reserve in advance, since otherwise a similar function will have to be called every single time push_back is called (which is far more costly).

I'm not sure whether I got this right, but I believe it was something along those lines.
Everytime push_back() reserves more space it has to copy the entire vector's contents to a new area of memory. It is therefore more efficient if you reserve() the right amount of memory to begin with.
Kyon - it's not everytime. I am not sure if this is guaranteed by the standard, but the normal procedure would be doubling the previous size (e.g. if a vector would start with a size of 10, 20 spaces would be reserved once the 11th element is pushed, 40 for the 21th element etc etc).
Topic archived. No new replies allowed.