2

In C++, to use complex numbers, I have the struct-type "creal" be defined as

  typedef struct {  
  double re;  
  double im; } creal;  

Now let "length" be the number of elements of the struct array "complex_vector" that is initilized as

creal complex_vector[length];

and is later filled with data.

I would like to extract the two arrays "real_vector" and "imag_vector" from "complex_vector". Until now I have used a for-loop:

double real_vector[length];
double imag_vector[length]; 
for (int n = 0; n < length; n++) 
{ 
    real_vector[n] = complex_vector[n].re;
    imag_vector[n] = complex_vector[n].im;
} 

I wonder if there is a way to avoid the for loop and extract the values of the struct array "complex_vector" directly to create the arrays "real_vector" and "imag_vector".

Thank you for your help.

4
  • 4
    c++ already has a complex number class: #include <complex> Commented May 7, 2014 at 9:31
  • I know but this is just an example. My question is more about how to extract arrays from struct arrays. Commented May 7, 2014 at 9:34
  • There is no other way. There are standard library constructs to iterate over the array and extract the values, but that simply shortens your code. Beneath it all you can't evade the loop. Commented May 7, 2014 at 9:38
  • Use std::transform. Commented May 7, 2014 at 9:39

2 Answers 2

1

the loop can not be a avoided since the data in your complex_vector is interleaved

re0 im0 re1 im1 re2 im2 ... reN imN

and your target rep is non interleaved

re0 re1 re2 ... reN
im0 im1 im2 ... imN

so the copying has to be done in any way. how ever you may write the code in a more compact form using some for_each magic but in my opinion this only makes the code more difficult to understand.

edit:
then using some more sophisticated Matrix classes (eg in OpenCV cv::Mat_) this copying can be avoided by using same data buffer but modifying the step size. but this of course comes at the cost of slower element access.

1

In principal there isn't. There are perhaps ways to write a better for-loop or hide it in a library call, but it will still be a for loop. Examples may be boost zip iterator or std::for_each.

However, your for loop is very simple and clean, so I would leave the code as it is.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.