RandomGuy
RandomGuy

Reputation: 125

std::transform to copy one array of struct to another

I have below structures.

typedef struct
{
    uint32_t   aa;        
    float32_t  bb;  
    float32_t  cc;  
    float32_t  dd;    
    float32_t  ee;    
}struct_1;

typedef struct
{
    uint32_t   hh;        
    float32_t  bb;  
    float32_t  cc;  
    float32_t  ii;    
    float32_t  jj;    
}struct_2;

I have created array of structures where struct_1 is dynamically allocated and struct_2 is static.

struct_1 *array1 = new struct_1[300];
struct_2 array2[300];

How to copy the contents efficiently from array2 to array1? I don't want to memcpy here because if in future types of any structure is changed then it will cause a problem.

Can i use std::transform or std::copy in this scenario? Please help me with the syntax.

Upvotes: 3

Views: 1218

Answers (2)

Artyer
Artyer

Reputation: 40801

It may be easier to work with a loop:

struct_1* a1_p = array1;
for (const struct_2& s2 : array2) {
    *a1_p++ = struct_1{ s2.hh, s2.bb, s2.cc, s2.ii, s2.jj };
}

This also lets you set only some members of struct_1 (for example, if you added more members and only wanted to override the corresponding members from struct_2):

struct_1* a1_p = array1;
for (const struct_2& s2 : array2) {
    struct_1& s1 = *a1_p++;
    s1.aa = s2.hh;
    s1.bb = s2.bb;
    s1.cc = s2.cc;
    s1.dd = s2.ii;
    s1.ee = s2.jj;
    // Any members not set will remain the same
}

Upvotes: 1

Mestkon
Mestkon

Reputation: 4046

You can use std::transform and supply a conversion function:

std::transform(std::begin(array2), std::end(array2), array1, [](const struct_2& val) {
     return struct_1{val.hh, val.bb, val.cc, val.ii, val.jj};
});

Upvotes: 8

Related Questions