C++ STL vector, erase(), begin() and end() 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++ begin() to return a random-access iterator to the first element in the container, end() return a random-access iterator that points just beyond the end of the vector and erase() to remove an element or a range of elements in a vector from specified positions in C++ programming

To show: How to use the C++ begin() to return a random-access iterator to the first element in the container, end() return a random-access iterator that points just beyond the end of the vector and erase() to remove an element or a range of elements in a vector from specified positions in C++ programming

 

// C++ STL vector, erase(), begin() and end()

#include <vector>

#include <iostream>

using namespace std;

 

int main(void)

{

// vector container

vector <int> vec1;

// vector iterator

vector <int>::iterator Iter;

 

// push data into the vector container

vec1.push_back(3);

vec1.push_back(7);

vec1.push_back(22);

vec1.push_back(5);

vec1.push_back(12);

vec1.push_back(17);

 

// print the data and do some operations

cout<<"Original vec1 vector data: ";

for(Iter = vec1.begin(); Iter != vec1.end(); Iter++)

cout<<" "<<*Iter;

cout<<endl;

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

vec1.erase(vec1.begin());

cout<<"After erase(), new vec1 vector data: ";

for(Iter = vec1.begin(); Iter != vec1.end(); Iter++)

cout<<" "<<*Iter;

cout<<endl;

cout<<"\nOperation: vec1.erase(vec1.begin()+1, vec1.begin()+3);"<<endl;

vec1.erase(vec1.begin() + 1, vec1.begin() + 3);

cout<<"After erase(), new vec1 vector data: ";

for(Iter = vec1.begin(); Iter != vec1.end(); Iter++)

cout<<" "<<*Iter;

cout<<endl;

return 0;

}

 

Output examples:

 

Original vec1 vector data: 3 7 22 5 12 17

Operation: erase(vec1.begin();

After erase(), new vec1 vector data: 7 22 5 12 17

Operation: vec1.erase(vec1.begin()+1, vec1.begin()+3);

After erase(), new vec1 vector data: 7 12 17

Press any key to continue . . .

 

 

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