Vectors have different methods to return the size details:
size:
Returns the number of elements in the vector container.
This is the number of actual objects held in the vector, which is not necessarily equal to its storage capacity. Vectors automatically reallocate their storage space when needed or when requested with member resize. To retrieve the current storage capacity of a vector you can call to its member capacity.
capacity:
Returns the size of the allocated storage space for the elements of the vector container.
Notice that, in vectors, the capacity is not necessarily equal to the number of elements that conform the underlying vector content (this can be obtained with member vector::size), but the capacity of the actual allocated space, which is either equal or greater than the content size.
Notice also that this capacity does not suppose a limit to the size of the vector. If more space is required to accomodate new elements in the vector, the capacity is automatically expanded, or can even be explicitly modified by calling member vector::reserve.
The real limit on the size a vector object can reach is returned by member vector::max_size.
max_size:
Returns the maximum number of elements that the vector container can hold.
This is not the amount of storage space currently allocated to the vector (this can be obtained with member vector::capacity), but the maximum potential size the vector could reach due to system or library implementation limitations.
Example:
[mingle]/home/rjanagam/CPP% cat stl_vector_sizes.cpp
#include
#include
using namespace std;
int main(void)
{
vector v;
v.reserve(5);
cout<< " size=" << v.size()<< ":capacity="<<v.capacity()<<":max_size="<<v.max_size()<<endl;
vector t;
cout<< " size=" << v.size()<< ":capacity="<<t.capacity()<<":max_size="<<t.max_size()<<endl;
vector r(5);
cout<< " size=" << r.size()<< ":capacity="<<r.capacity()<<":max_size="<<r.max_size()<<endl;
vector s(5);
s[0]=1,s[1]=2;
cout<< " size=" << s.size()<< ":capacity="<<s.capacity()<<":max_size="<<s.max_size()<<endl;
vector w;
w.push_back(1);
cout<< " size=" << w.size()<< ":capacity="<<w.capacity()<<":max_size="<<w.max_size()<<endl;
vector b;
for (int i=0;i<31;i++)
b.push_back(1);
cout<< " size=" << b.size()<< ":capacity="<<b.capacity()<<":max_size="<<b.max_size()<<endl;
vector x;
cout<< " size=" << x.size()<< ":capacity="<<x.capacity()<<":max_size="<<x.max_size()<<endl;
}
[mingle]/home/rjanagam/CPP% a.out
size=0:capacity=5:max_size=1073741823
size=0:capacity=0:max_size=1073741823
size=5:capacity=5:max_size=1073741823
size=5:capacity=5:max_size=1073741823
size=1:capacity=32:max_size=1073741823
size=31:capacity=32:max_size=1073741823
size=0:capacity=0:max_size=1073741823