vector::operator[] member function


Vector also support the subscript ‘[ ]’ operator which allows the 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.

First 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.

Code example

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

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

Output

12
48





Why is operator[] insecure?

Accessing the vector using the subscript ‘[]’ does not guarantee that a valid storage will be always accessed.Suppose in a vector having only four elements if the index value is written as 4 we will get an undefined output because no element with the index value 4 exists;the storage is past the size of the vector.

Code example

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

cout<< vec[4] ; //undefined

Output

undefined

When you get such error you might blame that it is the programmer’s fault for not considering the index value carefully.However,the operator[] is also to be blamed partly.At least the operator[] can give some error message or signal us that the index value is invalid and as such the error could have been avoided.The operator[] function does not check the validity of the index value,it only renders the value at the position provided as the index value.For this reason we consider accessing the vector using operator[ ] as insecure.

Vector has another member function:at(size_t),which makes sure that we always access the data at a valid storage.If we try to access the storage beyond the last element of the vector or in any invalid position it will signal us by throwing an exception.Throwing an exception makes the programmer know of the error which later(if no more error is found) ensures us that our program is free from bug(undefined value),which otherwise might appear if operator[ ] has been used.

Link:Read more about at(size_t) here.


 


Stop wasting time,earn money($$$) from your website-Join Now!