Using memcpy( ) With Arrays and Vectors.

Jan 9, 2011 at 3:41pm
closed account (zb0S216C)
Basically, can I use the memcpy( ) method when copying an integer from a vector to an integer array( and vice-versa )?

Here is what I mean:
1
2
3
4
5
6
7
8
9
// The vector which contains one integer with the value of seven.
vector < int > vIntVector( 1, 7 );

// The integer array which contains one integer with the value of zero.
int *pnIntArray( new int[ 1 ] );
pnIntArray[ 0 ] = 0;

// Copy the value from the vector to the integer array.
memcpy( pnIntArray, &vIntVector, sizeof( vIntVector ) );
Last edited on Jan 9, 2011 at 3:42pm
Jan 9, 2011 at 3:43pm
You can.
That's limited to int and other PODs, though.

Edit: but not like that. sizeof(vIntVector) certainly does not give the result you want and copying from &vIntVector is incorrect as well. The following works:

memcpy(pnIntArray,&vIntVector[0],sizeof(int)*vIntVector.size());
Last edited on Jan 9, 2011 at 3:47pm
Jan 9, 2011 at 3:46pm
closed account (zb0S216C)
Thanks Athar!.
Jan 9, 2011 at 5:43pm
note you should prefer std::copy over memcpy. Especially when dealing with STL containers:

1
2
3
4
5
// basically it works like this:
std::copy( src, src + size, dest );

// so, you would do this:
std::copy( pnIntArray, pnIntArray + 1, vIntVector.begin() );
Jan 10, 2011 at 2:17am
in this case, I think the assign member function of the vector itself would be the best choice
atlease use copy rather than memcpy
stl has its own coding style
when you work with stl, you better follow the way stl should be
Last edited on Jan 10, 2011 at 2:19am
Topic archived. No new replies allowed.