C++ vector::operator[] member function

In C++ vector also support the operator[](uses the subscript ‘[ ]’) which allow access of the element in any position in the vector.

T& operator[ ](size_t n);
const T& operator[ ](size_t n);
First function

Parameters:
n – The index of the element for which the data is to accessed.

Return type
T& – A read and write reference to the data.

Second function

Parameters:
n – The index of the element for which the data is to accessed.

Return type
T& – A read only reference to the data.

Note accessing the element of the vector using this operator is insecure(why? explain later) ,you should consider using the function at( size_t ),for secure access of the vector data.

 vector<int> vec={ 12 , 4 , 48 , 90 };

cout<< vec[0] << endl //access the first element
<< vec[2] ; //Access the third element

Output

12
48



Leave a Reply

Your email address will not be published. Required fields are marked *