C++ STL vector operator[ ] 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++ vector operator[ ] to return a reference to the vector element at a specified position in C++ programming

To show: How to use the C++ vector operator[ ] to return a reference to the vector element at a specified position in C++ programming

 

// C++ STL vector operator[]

#include <vector>

#include <iostream>

using namespace std;

 

int main(void)

{

// vector container

vector <int> vec1;

unsigned int i;

 

// push/insert data

vec1.push_back(10);

vec1.push_back(9);

vec1.push_back(8);

vec1.push_back(12);

 

// print the data

cout<<"vec1 vector data: ";

for(i=0; i<vec1.size(); ++i)

cout<<vec1[i]<<' ';

cout<<endl;

cout<<"Operation: int& j = vec1[2];"<<endl;

int& j = vec1[2];

cout<<"The third integer of vec1 vector is "<<j<<endl;

return 0;

}

 

Output examples:

 

vec1 vector data: 10 9 8 12

Operation: int& j = vec1[2];

The third integer of vec1 vector is 8

Press any key to continue . . .

 

 

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