C++ vector::data function

The C++ vector data() function returns a pointer to the vector element.There are two types of data() function.

T :type of data.

T* data( );
const T* data( ) const;

First function

Return type :
T* – A pointer to the vector element.
Second function

Return type :
const T* – A const pointer to the vector element.

The difference between the first and second function being that the first function returns a non-constant pointer whereas the second fucntion returns a constant pointer.

If the vector is empty ,the data( ) function returns 0.If the vector capacity is non-zero or it is non-empty ,the data() function returns the address of the first storage.So data() == &front().

 vector<int> vec ={ 12 , 343 , 89 } ,
vec1 ;

cout<< vec.data() << endl
<< &vec.front() << endl ;

cout<< vec1.data() << endl ;

vec1.reserve(2) ;

cout<< vec1.data( ) << endl
<< &vec1.front( ) << endl ;

Output in my computer


Before any memory is reserve calling vec1.data() returns 0,but after reserving some storage the data() returns the address of the first storage.


One probable use of data( ) function is to assign an address of the element at any position of a vector to a pointer.If the position of the element you want to assign to another pointer is other than the first position.You can simply add a value to the data() function,this value will determine the returned address of the element counting from the front.

vector<int> vec={ 1 , 90 , 128 };

int *iPt=vec.data() ; ///iPt assigned the first element address

cout<< *iPt << endl ;

int *ptNew=vec.data( )+2 ; //ptNew assigned the address of the third element

cout<< *ptNew << endl ;




Using data() to assign the address of the element to smart pointers can be dangerous.If the smart pointer goes out of scope the storage pointed by it will also get destroyed.This in turn will make the storage invalid,hence accessing it will give an undefined result.


shared_ptr<int> sp( vec.data( ) ) ; //sp assigned the front address
cout<< *sp << endl ;

}//front storage gets destroyed here

cout<< vec[0] ; //undefined


undefined (some random value)

Leave a Reply

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