C++ STL vector, reserve(), 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++ reserve() to reserve a minimum length of storage for a vector object, size() to return the number of elements in the vector, capacity() to return the number of elements that the vector could contain without allocating more storage in C++ programming

To show: How to use the C++ reserve() to reserve a minimum length of storage for a vector object, size() to return the number of elements in the vector, capacity() to return the number of elements that the vector could contain without allocating more storage in C++ programming

 

// C++ STL vector, reserve(), capacity() and size()

#include <vector>

#include <iostream>

using namespace std;

 

int main(void)

{

// vector container

vector <int> vec1;

unsigned int i;

 

// push/insert data

vec1.push_back(4);

vec1.push_back(2);

vec1.push_back(10);

 

// print the data  and do some operations

cout<<"vec1 vector data: ";

for(i=0; i<vec1.size(); ++i)

cout<<vec1[i]<<' ';

cout<<endl;

cout<<"\nOperation: vec1.capacity();"<<endl;

cout<<"Current capacity of vec1 vector is "<<vec1.capacity()<<endl;

cout<<"\nOperation: vec1.reserve(10);"<<endl;

vec1.reserve(10);

cout<<"Current capacity of vec1 vector is "<<vec1.capacity()<<endl;

cout<<"\nOperation: vec1.size()"<<endl;

cout<<"Current size of vec1 vector is "<<vec1.size()<<endl;

return 0;

}

 

Output examples:

 

vec1 vector data: 4 2 10

Operation: vec1.capacity();

Current capacity of vec1 vector is 3

Operation: vec1.reserve(10);

Current capacity of vec1 vector is 10

Operation: vec1.size()

Current size of vec1 vector is 3

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index