C++ STL vector, clear(), empty() 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++ clear() to erase the elements of the vector, empty() to test if the vector container is empty and size() to return the number of elements in the vector in C++ programming

To show: How to use the C++ clear() to erase the elements of the vector, empty() to test if the vector container is empty and size() to return the number of elements in the vector in C++ programming

 

// C++ STL vector, clear(), empty() and size()

#include <vector>

#include <iostream>

using namespace std;

 

int main(void)

{

// vector container

vector <int> vec1;

unsigned int i;

 

// push data into vector container

vec1.push_back(10);

vec1.push_back(20);

vec1.push_back(30);

 

// print the data and do some operations

cout<<"vec1 vector data: ";

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

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

cout<<endl;

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

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

if(vec1.empty())

cout<<"vec1 vector is empty"<<endl;

else

cout<<"vec1 vector is not empty"<<endl;

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

vec1.clear();

cout<<"The size of vec1 vector after clearing is "<<vec1.size()<<endl;

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

if(vec1.empty())

cout<<"vec1 is empty"<<endl;

else

cout<<"vec1 is not empty"<<endl;

return 0;

}

 

Output examples:

 

vec1 vector data: 10 20 30

The size of vec1 vector is 3

Operation: vec1.empty();

vec1 vector is not empty

Operation: vec1.clear();

The size of vec1 vector after clearing is 0

Operation: vec1.empty();

vec1 is empty

Press any key to continue . . .

 

 

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