Thread: don't understand myVector.reserve(numSpaces)

  1. #1
    Registered User
    Join Date
    Mar 2008

    don't understand myVector.reserve(numSpaces)

    I'm going through a book and I've looked this up, but don't understand why (or maybe I have to) use reserve. Since it is a vector why is there a need to reserve memory? Is it just a way so that it doesn't double the memory off the heap or something (me guessing)?

    here is the code I am looking at:
    class Farm
        Farm(int spaces = 1);
        //.... more stuff goes here
        vector<myFarmAnimalClassObject> m_farmAnimal;
    //=============Constructor: reserve used below=========
    Farm::Farm(int spaces)
        m_farmAnimal.reserve(spaces)    //  <===  reserve?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    It is an optimisation. The idea is that instead of having the vector grow incrementally, you can let it allocate the minimum amount of space you know that you will need, and only grow further if your prediction was not good enough. As such, all the push_back()s up to the reserve point will not result in re-allocation (which is a good thing if you do not want re-allocations to occur because you have say, iterators to the container that you do not want invalidated).

    On the other hand, read what Stroustrup has to say about slow containers, in particular the last paragraph.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Mar 2008
    Thanks again! I never thought about iterators. Reading that artical made me think about other things I don't know and will have to experiement with (pointers to an unsorted list which is then sorted - I'm sure it comes out ok, but I've never thought of it till now). I've mostly just messed around with python which doesn't really use pointers.

    Well, now its more fun with farm animals! ! !

Popular pages Recent additions subscribe to a feed
Website Security Test