Skip to content

vector_pro::reserve

C++
void reserve(const size_type re_size);

Request a change in capacity

Requests that the vector capacity be at least enough to contain re_size elements.

If n is greater than the current vector capacity, the function causes the container to reallocate its storage increasing its capacity to re_size (or greater).

In all other cases, the function call does not cause a reallocation and the vector capacity is not affected.

This function has no effect on the vector size and cannot alter its elements.

Parameters

  1. re_size
    Minimum capacity for the vector.

Return value

none

Example

C++
// vector_pro::reserve
#include <iostream>
#include "vector_pro.h"

/**
 * Output:
 * making foo grow:
 * capacity changed: 128
 * making bar grow:
 * capacity changed: 100
 */

int main ()
{
  size_type sz;

  vector_pro<int> foo;
  sz = foo.capacity();
  std::cout << "making foo grow:\n";
  for (int i=0; i<100; ++i) {
    foo.push_back(i);
    if (sz!=foo.capacity()) {
      sz = foo.capacity();
      std::cout << "capacity changed: " << sz << '\n';
    }
  }

  vector_pro<int> bar;
  sz = bar.capacity();
  bar.reserve(100);   // this is the only difference with foo above
  std::cout << "making bar grow:\n";
  for (int i=0; i<100; ++i) {
    bar.push_back(i);
    if (sz!=bar.capacity()) {
      sz = bar.capacity();
      std::cout << "capacity changed: " << sz << '\n';
    }
  }
  return 0;
}

Complexity

If a reallocation happens, linear in vector size at most.