vector::at function


The ‘vector at‘ function access the element of the vector at a specified position.

T& at( size_t n ) ;
const T& at( size_t n ) const;

First function

Parameters:
n – The position at which the element is to be accessed.

Return type
T& – A read and write reference of the vector at a specified position.

Second function

Parameters:
n – The position at which the element is to be accessed.

Return type
const T& – A read only reference of the vector at a specified position.

If the position specified is invalid std::out_of_range exception is thrown.The position is considered as invalid if it is a negative value or it is beyond the range of the vector.

This function is safer than using the operator[ ] to access the data of the vector.The operator[] does not check if the index is valid or invalid and so at times we get an undefined output is the specified position is invalid(shown later how?).The at(size_t) function however ensures that the specified position is valid,and if it is invalid it notify us by throwing an exception.

Code example:Accessing the value with at(size_t)

vector<double> vecD={ 12.34 , 4.8 , 0.08 , 78 };

cout<< vecD.at(2) ; ///access the value at third position
<< vecD[2] ; ///ditto as above

Output

0.08

Code example:Changing the value with at(size_t) .

vecD.at(3) =5.34 ; //change value at 3rd position

cout<< vecD.at(3) ;

Output

5.34

Code example:why at(size_t) is more secure than operator[].

cout<< vecD.at( 4 ) ; ///throws std:out_of_range exception

cout<< vecD[4] ; ///gives undefined value

There is no 4th index element ( 5th element ) in vecD vector ,this position is invalid.