C++ STL vector, insert(), 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++ insert() to insert() an element or a number of elements into the vector at a specified position, begin() to return a random-access iterator to the first element in the container and end() to return a random-access iterator that points just beyond the end of the vector in C++ programming

To show: How to use the C++ insert() to insert() an element or a number of elements into the vector at a specified position, begin() to return a random-access iterator to the first element in the container and end() to return a random-access iterator that points just beyond the end of the vector in C++ programming

 

// C++ STL vector, insert(), 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/insert data

vec1.push_back(12);

vec1.push_back(100);

vec1.push_back(9);

vec1.push_back(21);

 

// 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: vec1.insert(vec1.begin()+1, 17)"<<endl;

vec1.insert(vec1.begin()+1, 17);

cout<<"New vec1 vector data: ";

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

cout<<" "<<*Iter;

cout<<endl;

cout<<"\nOperation: vec1.insert(vec1.begin()+2, 3, 24)"<<endl;

vec1.insert(vec1.begin()+2, 3, 24);

cout<<"New vec1 vector data: ";

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

cout<<" "<<*Iter;

cout<<endl;

cout<<"\nOperation: vec1.insert(vec1.begin()+1, vec1.begin()+2, vec1.begin()+4)"<<endl;

vec1.insert(vec1.begin()+1, vec1.begin()+2, vec1.begin()+4);

cout<<"New vec1 vector data: ";

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

cout<<" "<<*Iter;

cout<<endl;

return 0;

}

 

Output examples:

 

Original vec1 vector data: 12 100 9 21

Operation: vec1.insert(vec1.begin()+1, 17)

New vec1 vector data: 12 17 100 9 21

Operation: vec1.insert(vec1.begin()+2, 3, 24)

New vec1 vector data: 12 17 24 24 24 100 9 21

Operation: vec1.insert(vec1.begin()+1, vec1.begin()+2, vec1.begin()+4)

New vec1 vector data: 12 24 24 17 24 24 24 100 9 21

Press any key to continue . . .

 

 

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