C++ STL vector, at() 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++ at() to return a reference to the element at a specified location in the vector in C++ programming
To show: How to use the C++ at() to return a reference to the element at a specified location in the vector in C++ programming
// C++ STL vector, at()
#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(1);
vec1.push_back(7);
vec1.push_back(4);
vec1.push_back(3);
// print all elements separated by a space
cout<<"The vec1 vector data: ";
for(i=0; i<vec1.size(); ++i)
cout<<vec1[i]<<' ';
cout<<"\n\nOperation: vec1.at(position);"<<endl;
const int &x = vec1.at(1);
int &y = vec1.at(3);
int &z = vec1.at(0);
cout<<"\nThe 2nd element is "<<x<<endl;
cout<<"The 4th element is "<<y<<endl;
cout<<"The 1st element is "<<z<<endl;
return 0;
}
Output examples:
The vec1 vector data: 1 7 4 3
Operation: vec1.at(position);
The 2nd element is 7
The 4th element is 3
The 1st element is 1
Press any key to continue . . .