C++ STL vector, back() and front() 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++ back() to return a reference to the last element of the vector and front() to return a reference to the first element in a vector in C++ programming
To show: How to use the C++ back() to return a reference to the last element of the vector and front() to return a reference to the first element in a vector in C++ programming
// C++ STL vector, back() and front()
#include <vector>
#include <iostream>
using namespace std;
int main(void)
{
// vector containers
vector <int> vec1, vec2;
unsigned int i;
// push data into vector container
vec1.push_back(12);
vec1.push_back(10);
vec1.push_back(7);
// print all elements separated by a space
cout<<"vec1 vector data: ";
for(i=0; i<vec1.size(); ++i)
cout<<vec1[i]<<' ';
cout<<endl;
int& x = vec1.back();
const int& y = vec1.front();
cout<<"\nOperation: x = vec1.back();"<<endl;
cout<<"The last integer of vec1 vector is "<<x<<endl;
cout<<"Operation: y = vec1.front();"<<endl;
cout<<"The 1st integer of vec1 vector is "<<y<<endl;
return 0;
}
Output examples:
vec1 vector data: 12 10 7
Operation: x = vec1.back();
The last integer of vec1 vector is 7
Operation: y = vec1.front();
The 1st integer of vec1 vector is 12
Press any key to continue . . .