C++ STL vector, resize() 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++ size() to return the number of elements in the vector and resize() to specify a new size for a vector in C++ programming
To show: Using the C++ size() to return the number of elements in the vector and resize() to specify a new size for a vector in C++ programming
// C++ STL vector, resize() and size()
#include <vector>
#include <iostream>
using namespace std;
int main(void)
{
unsigned int i;
// vector container
vector <int> vec1;
// push data into the container
vec1.push_back(40);
vec1.push_back(20);
vec1.push_back(10);
vec1.push_back(12);
// print the data
cout<<"vec1 vector data: ";
for(i=0; i<vec1.size(); ++i)
cout<<vec1[i]<<' ';
cout<<endl;
// resize to 5 and add data at the end
cout<<"\nOperation: vec1.resize(5,30);"<<endl;
vec1.resize(5,30);
cout<<"The size of vec1 vector is "<<vec1.size()<<endl;
cout<<"The value of the last object is "<<vec1.back()<<endl;
cout<<"\nNew vec1 vector data: ";
for(i=0; i<vec1.size(); ++i)
cout<<vec1[i]<<' ';
cout<<endl;
cout<<"\nOperation: vec1.resize(4);"<<endl;
vec1.resize(4);
cout<<"\nNew vec1 vector data: ";
for(i=0; i<vec1.size(); ++i)
cout<<vec1[i]<<' ';
cout<<endl;
cout<<"\nThe new size of vec1 vector is "<<vec1.size()<<endl;
cout<<"The value of the last object is "<<vec1.back()<<endl;
return 0;
}
Output examples:
vec1 vector data: 40 20 10 12
Operation: vec1.resize(5,30);
The size of vec1 vector is 5
The value of the last object is 30
New vec1 vector data: 40 20 10 12 30
Operation: vec1.resize(4);
New vec1 vector data: 40 20 10 12
The new size of vec1 vector is 4
The value of the last object is 12
Press any key to continue . . .