Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

c++14

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.

like image 551
RandomGuy Avatar asked Dec 11 '25 17:12

RandomGuy


1 Answers

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};
});
like image 85
Mestkon Avatar answered Dec 13 '25 07:12

Mestkon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!