vector::data function


The data() function returns a pointer to the vector element.

T :type of data.

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

First function
Parameters:
none

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

Second function
Parameters:
none

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

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 or element.So data() == &front().

Code example

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

0xd716d0
0xd716d0
0
0xd71710
0xd71710

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





Use

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.

Code example

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 ;

Output
1
128

Beware!

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.

Link:Smart pointer : Shared pointer ; why is it call shared pointers?

Code example

{

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

}///front storage gets destroyed here

cout<< vec[0] ; //undefined

Output

1
undefined (some random value)


 


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