【问题标题】:Brace-enclosed initializer for matrix constructor fail in type std::complex<double> >矩阵构造函数的大括号封闭初始化程序在 std::complex<double> 类型中失败
【发布时间】:2020-12-02 17:36:02
【问题描述】:

我为我的矩阵类实现了一个构造函数,以使用嵌套的 std::initializer_list 进行大括号括起来的初始化。构造函数适用于主要类型:`int`、`double`;但会为“复杂”呈现错误读取。如何解决此错误阅读?

矩阵类

template <typename T> class xxx
{
 public:
     T *ptr;
     int col, row, size;
     xxx() = delete;
     xxx(const int i, const int j):row(i), col(j), size(i*j)
     {
         ptr = new T [this->size] ;
     }
     xxx(const std::initializer_list< std::initializer_list<T> > s):xxx(s.size(), s.begin()->size())
     {
       int j = 0;
       for (const auto& i : s) {  std::copy (i.begin(), i.end(), ptr + j*col); ++j ; }
    }
    ~xxx() {delete [] this->ptr;}
     T operator()(const int i, const int j) const { return ptr[i*col+j]; }
};

这里添加了一个典型的输出过载来完成。

template <typename X> std::ostream& operator<<(std::ostream&p, const xxx<X>&a)
{
    for (int i=0; i<a.row; i++) {
        for (int j=0; j <a.col; j++) p << std::setw(6) << a(i, j);
        p << std::endl;
    }
    return p;
}

`double` 类型的第一个测试 main() 运行良好。

#include <iostream>
#include <initializer_list>
#include <iomanip>
#include <complex>
int main()
{
    xxx<double> x = {{1, 2,3,4} , {3, 4,5,6}, {5, 6,7,8} };
    std::cout << x << std::endl;
}

它打印预期的内容:

$ ./a.exe
     1     2     3     4
     3     4     5     6
     5     6     7     8

然后,我尝试另一种我感兴趣的类型,`complex`:

int main()
{
    xxx< std::complex<double> > z = { {(1,2), (3,4)}, {(5,6), (7,8)} };
    std::cout << z << std::endl;
}

输出错误如下:

$ ./a.exe
 (2,0) (4,0)
 (6,0) (8,0)

缺少想象部分,真实部分取反想象部分的值。任何想法或建议都将受到高度赞赏。

【问题讨论】:

  • 你能发一个minimal reproducible example吗?没有你的operator&lt;&lt;,我看不到代码的输出
  • 为完整性添加了输出过载。

标签: c++ c++11 complex-numbers list-initialization


【解决方案1】:

您的问题与初始化列表无关。问题是这段代码

#include <iostream>
#include <complex>

int main()
{
    std::complex<double> x = (1,2);
    std::cout << x;
}

没有做你期望它做的事情。输出是

(2,0)

因为(1,2) 是工作中的comma operator。 std::complex&lt;double&gt; x = (1,2); 与 std::complex&lt;double&gt; x = 2; 相同。

您需要使用花括号进行初始化:

#include <iostream>
#include <complex>

int main()
{
    std::complex<double> x = {1,2};
    std::cout << x;
}

输出

(1,2)

PS 我强烈建议您使用 std::vector&lt;T&gt; 而不是 T* 来保存数据。目前复制 xxx 会导致未定义的行为,因为不遵循 3/5 规则。

【讨论】:

  • @largest-prime-is-463035818 谢谢。 (real, imah) 是复数文件 i/o 中的常规格式。我太习惯于对位形式了。对于针对大约 500x500 的 natrix 的数值工作者来说,std::vector 不是一个实用的选择,我确实在 c99 中有一个用于 Hermitian 和 sysmetric eigen 问题的矩阵类,并尝试使用一些更新的语言协议进行更新,
  • @ytlu “std::vector 不是一个实用的选择”你为什么这么认为?如果T* 可以做到,那么std::vector 也可以做到。
  • @maximum_prime_is_463035818 例如,要复制一个大矩阵,将执行内存复制而不是元素到元素的分配。我想知道您是否可以在 std::vector 结构中节省内存复制?
  • @ytlu 是的,你可以。当我说“如果T* 可以做到,那么std::vector 也可以做到”,我的意思就是这样;)
  • @ytlu 我不是在谈论std::vector&lt;std::vector&lt;T&gt;&gt;,以防那是误解。嵌套向量确实有严重的缺点
猜你喜欢
  • 2011-05-06
  • 2023-04-10
  • 2013-09-16
  • 1970-01-01
  • 2015-02-02
  • 2012-04-16
  • 1970-01-01
  • 2016-02-16
相关资源
最近更新 更多