top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration

Facebook Login
Site Registration

CPP : How the method "capacity()" of vector class work ?

+1 vote

I am looking for an example with explanation that elaborate the functioning of capacity method.

posted Sep 5, 2016 by Neelam

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

it returns the size of the storage space currently allocated for the vector, expressed in terms of elements.This capacity is not necessarily equal to the vector size. It can be equal or greater, with the extra space allowing to accommodate for growth without the need to reallocate on each insertion.
This capacity does not suppose a limit on the size of the vector. When this capacity is exhausted and more is needed, it is automatically expanded by the container. The theoretical limit on the size of a vector is given by member max_size.

  #include <iostream>
    #include <vector>
    using namespace std;
    int main ()
      vector<int> myvector;
      for (int i=0; i<100; i++)
      cout << "size: " << (int) myvector.size() << endl;
      cout << "capacity: " << (int) myvector.capacity() << endl;
      cout << "max_size: " << (int) myvector.max_size() << endl;
      return 0;

complexity of capacity() = O(1)
Output of above code:
size: 100
capacity: 128
max_size: **********

answer Sep 6, 2016 by Shivam Kumar Pandey
Similar Questions
0 votes

Is "cpp -P" POSIX? I poked around at**********

and could find only matches to "preprocessor" rather than "cpp" in the search facility, and so surmise "no", but thought i'd ask here anyway. I suppose a portable workaround would be:

cpp FILENAME | sed '/^#/d'

but have fingers crossed nonetheless...

Contact Us
+91 9880187415
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Karnataka INDIA.