C++ STL vector, capacity() and size() code example
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard
Additional library: none/default
Additional project setting: Set project to be compiled as C++
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)
Other info: none
To do: Using the C++ capacity() to return the number of elements that the vector could contain without allocating more storage and size() to return the number of elements in the vector in C++ programming
To show: How to use the C++ capacity() to return the number of elements that the vector could contain without allocating more storage and size() to return the number of elements in the vector in C++ programming
// C++ STL vector, capacity() and size()
#include <vector>
#include <iostream>
using namespace std;
int main(void)
{
// vector container
vector <int> vec1;
unsigned int i;
// push data into container
vec1.push_back(3);
vec1.push_back(1);
vec1.push_back(6);
// print the data
cout<<"vec1 vector data: ";
for(i=0; i<vec1.size(); ++i)
cout<<vec1[i]<<' ';
cout<<endl;
cout<<"Operation: vec1.capacity();"<<endl;
cout<<"The length of storage allocated is "<<vec1.capacity()<<endl;
// push more data and print
vec1.push_back(10);
vec1.push_back(12);
vec1.push_back(4);
cout<<"\nnew vec1 vector data after push_back(): ";
for(i=0; i<vec1.size(); ++i)
cout<<vec1[i]<<' ';
cout<<endl;
cout<<"The length of storage allocated is now "<<vec1.capacity()<<endl;
return 0;
}
Output examples:
vec1 vector data: 3 1 6
Operation: vec1.capacity();
The length of storage allocated is 3
new vec1 vector data after push_back(): 3 1 6 10 12 4
The length of storage allocated is now 6
Press any key to continue . . .