don't understand myVector.reserve(numSpaces)

This is a discussion on don't understand myVector.reserve(numSpaces) within the C++ Programming forums, part of the General Programming Boards category; I'm going through a book and I've looked this up, but don't understand why (or maybe I have to) use ...

  1. #1
    Registered User
    Join Date
    Mar 2008
    Posts
    9

    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:
    Code:
    class Farm
    {
    public:
        Farm(int spaces = 1);
        //.... more stuff goes here
    
    private:
        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
    Location
    Singapore
    Posts
    21,719
    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.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Mar 2008
    Posts
    9
    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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21