3

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.

2
  • 2
    you can write a loop to copy the members, an algorithm also wouldn't do anything substantially different Commented Jun 5, 2020 at 14:19
  • 2
    Also, in C++, structs are classes, which means they are types. There is no need for a typedef. In your case, struct struct_1 { // }; will suffice. Commented Jun 5, 2020 at 14:29

2 Answers 2

8

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};
});
Sign up to request clarification or add additional context in comments.

1 Comment

Nice answer, but eventually use cbegin() instead of begin().
1

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.