C++ STL vector, begin() 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 in C++ programming
To show: How to use the C++ begin() to return a random-access iterator to the first element in the container in C++ programming
// C++ STL vector, begin()
#include <vector>
#include <iostream>
using namespace std;
int main(void)
{
// vector container
vector <int> vec1;
// vector iterator
vector <int>::iterator vec1_Iter;
unsigned int i;
// push data into container
vec1.push_back(21);
vec1.push_back(12);
vec1.push_back(32);
// print the data
cout<<"vec1 vector data: ";
for(i=0; i<vec1.size(); ++i)
cout<<vec1[i]<<' ';
cout<<endl;
cout<<"\nOperation: vec1.begin();"<<endl;
vec1_Iter = vec1.begin();
cout<<"The first element of vec1 vector is "<<*vec1_Iter<<endl;
cout<<"\nOperation: *vec1_Iter = 10;"<<endl;
*vec1_Iter = 10;
cout<<"new vec1 vector data: ";
for(i=0; i<vec1.size(); ++i)
cout<<vec1[i]<<' ';
cout<<endl;
cout<<"Operation: vec1.begin();"<<endl;
vec1_Iter = vec1.begin();
cout<<"The first element of vec1 vector is now "<<*vec1_Iter<<endl;
return 0;
}
Output examples:
vec1 vector data: 21 12 32
Operation: vec1.begin();
The first element of vec1 vector is 21
Operation: *vec1_Iter = 10;
new vec1 vector data: 10 12 32
Operation: vec1.begin();
The first element of vec1 vector is now 10
Press any key to continue . . .