Does vector function reserve() allocates space?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bajajv
    New Member
    • Jun 2007
    • 152

    Does vector function reserve() allocates space?

    Hi, I have gone thru a tutorial about vectors in cppreference.co m and it says that the reserve() function in vector allocates space for vector. But if I allocate some space for vector and try to give some value using the [] operator, it crashes.

    Code:
    vector<int> vect;
    vect.reserve(5);
    
    cout << "Capacity - " << vect.capacity() << endl; //it gives 5
    
    vect[0] = 10; //it crashes, saying out of range value given
    What is the use of vector function() reserve?
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    reserve() requests a change in vector capacity ready for a change in size later


    try running
    Code:
    int main()
    {
    vector<int> vect;
    vect.reserve(5);
    
    cout << "Capacity - " << vect.capacity() << endl; //it gives 5
    cout << "size - " << vect.size() << endl; //it gives 5
    vect.resize(5);
    cout << "Capacity - " << vect.capacity() << endl; //it gives 5
    cout << "size - " << vect.size() << endl; //it gives 5
    vect[4] = 10; //it crashes, saying out of range value given
    vect.at(4) = 10; //it crashes, saying out of range value given
    cout << vect[4] << endl;
    
    }
    one would use reserve() to allocate capacity so that the vector does not have to be reallocated every time the current capacity is exceeded
    I would also recommend that you use the at() method rather than operator[] as it checks for out of range and throws an exception - operator[] does not throw an exception - the program may carry on and crash later or give a memory segmentation error

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      When you reserve space in a vector does not add elements. The operator[] ony works for elements that exist and can cuase a crash if the index value is greater than the size of he vector.

      This behavior duplicates the behavior of the [] operator used on an array. vector is required to implement an array hence the same behavior in accessing loctions outside the array bounds.

      Comment

      • bajajv
        New Member
        • Jun 2007
        • 152

        #4
        Thanks for the responses.

        Comment

        Working...