C++ Vector Library - reserve() Function



Description

The C++ function std::vector::reserve() requests to reserve vector capacity be at least enough to contain n elements. Reallocation happens if there is need of more space.

Declaration

Following is the declaration for std::vector::reserve() function form std::vector header.

C++98

void reserve (size_type n);

Parameters

n − Minimum capacity for vector.

Return value

None

Time complexity

If realloaction happens then time complexity is linear i.e O(n).

Example

The following example shows the usage of std::vector::reserve() function.

In below example initial size of vector v1 is zero. After inserting first element vector is expanded and it's capacity becomes 1, after inserting next element it's capacity becomes 2 and so on. Vector increases it's capacity in power of two's as needed.

For vector v2 we are reserving capacity to hold 25 elements, that is why as soon as first element is inserted vector's capacity becomes 25.

#include <iostream>
#include <vector>

using namespace std;

int main(void) {
   vector<int> v1;
   vector<int> v2;
   ssize_t size;

   size = v1.capacity();

   for (int i = 0; i < 25; ++i) {
      v1.push_back(i);
      if (size != v1.capacity()) {
         size = v1.capacity();
         cout << "Expanding vector v1 to hold " << size
            << " elements" << endl;
      }
   }

   cout << endl << endl;

  /* Reserve space for 25 elements */
   v2.reserve(25);

   for (int i = 0; i < 25; ++i) {
      v2.push_back(i);
      if (size != v2.capacity()) {
         size = v2.capacity();
         cout << "Expanding vector v2 to hold " << size
            << " elements" << endl;
      }
   }
   return 0;
}

Let us compile and run the above program, this will produce the following result −

Expanding vector v1 to hold 1 elements
Expanding vector v1 to hold 2 elements
Expanding vector v1 to hold 4 elements
Expanding vector v1 to hold 8 elements
Expanding vector v1 to hold 16 elements
Expanding vector v1 to hold 32 elements
Expanding vector v2 to hold 25 elements
vector.htm
Advertisements