将双 * 转换为复杂 * [英] casting double * to complex*

查看:32
本文介绍了将双 * 转换为复杂 *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 double * 转换为 complex* .我只有一个 2x2 矩阵 D(双)的例子,我想把它转换为复杂的(C):

I am trying to cast double * to complex* . I just have an example of a 2x2 matrix D (double) and i want to cast it as complex (C):

typedef complex<double> dcmplx;

 int main() {

   dcmplx *C;
   double *D;
   int N=2;

   D=new double[N*N];
   C=new dcmplx[N*N];
   *C=static_cast<dcmplx>(*D);

   for (int i=0;i<N;i++){
     for (int j=0;j<N;j++){
      D[i*N+j]=i+j;
     }
   }


    for (int i=0;i<N;i++){
     for (int j=0;j<N;j++){
      cout <<D[i*N+j]<<"\t";
     }
     cout <<"\n";
   }


   cout <<"\n\n";
   cout <<"Complex\n";
   for (int i=0;i<N;i++){
     for (int j=0;j<N;j++){
      cout <<C[i*N+j]<<"\t";
     }
     cout <<"\n";
   }


  return 0; 

 }

这是正确的做法吗?

推荐答案

首先 std::complexdouble 是不兼容的类型,因此通过 static_cast 是不可能的.

Firstly the std::complex<double> and double are incompatible types therefore the casting via static_cast is not possible.

您可以使用 std::complex 的可用标准运算符进行转换,看看这里 http://www.cplusplus.com/reference/complex/complex/运算符/

You can use available standard operators for std::complex to do conversions, have a look here http://www.cplusplus.com/reference/complex/complex/operators/

下面是一个虚拟的转换示例,这只是一个使用 std::copy 找到优雅解决方案的示例,或者可能使用其他 STL 算法!我永远不会在我的最终源代码中使用这样的代码:)

A dummy example of conversion find below, this is just an example find an elegant solutions with std::copy or might be with other STL algorithms ! I'll never use such a code in my final source code :)

for (size_t i = 0; i < N * N; i++)
{
   *C = *D;   
   D++;
   C++;
}

最后,如果这两种类型以某种方式兼容,您必须像这样正确地进行指针的转换.

And finally if the two types were somehow compatible you have to do the casting of the pointers correctly like this.

C = static_cast(D);

更新:为你准备了一个很好的例子,享受:)

UPDATE : Prepared a good example for you, enjoy :)

   std::vector< std::complex<double> > C (N*N);
   double* D = new double[N*N];
   // initialization of D's elements
   C.assign(D, D + N*N);

这篇关于将双 * 转换为复杂 *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆