Copy an Array of structs

Apr 27, 2011 at 8:34am
Hi,

In my C++ code I have a Structs Array and I want to move the data from one position to another.
Is there a C++ function that lets you to do it easily, withouht having to make for loops to copy it.

Thanks a lot.

Regards,

Maria.
Apr 27, 2011 at 8:51am
Apr 27, 2011 at 10:25am
Sorry, I didn't explain myself correctly.

The array is initialized with "new T_TYPE_STRUCT[number]." To use less memory.

And inside that struct there are more arrays and structures.

Thanks a lot!
Regards,

Maria.
Apr 27, 2011 at 11:00am
But m4ster r0shi is still right:


1
2
3
T_TYPE_STRUCT *tts = new T_TYPE_STRUCT[number];

std::copy(tts, tts + number, new_pos);


This is only valid if 'new_pos' is outside [tts, tts + number)
Apr 27, 2011 at 11:14am
Okay, you can still use copy, like this:

1
2
3
4
5
6
7
8
9
10
//...

Struct * array=new Struct[N];

//...

Struct * array2=new Struct[N];
copy(array,array+N,array2);

//... 

Or... Is this an initialization problem? If it's an initialization problem
and all the elements of the array are supposed to have the same,
specific value, you could use the fill_n function, like this:

1
2
3
4
5
6
7
8
9
10
//...

Struct element;

//set element's value somehow...

Struct * array=new Struct[N];
fill_n(array,N,element);

//... 

http://cplusplus.com/reference/algorithm/fill_n/

If it's an initialization problem but the value of each element
depends on its position in the array, I'm afraid you have to
resort to loops. There are still things you can do though.
For example, writing constructors for your structs could help.

EDIT: Wow... I've been writing this reply for more than 15 minutes...
Last edited on Apr 27, 2011 at 11:19am
Apr 27, 2011 at 1:22pm
Thank you very much. Very useful. :D:D

Regards,

María
Topic archived. No new replies allowed.