如何在映射 C++ 中使用复数

How to use complex numbers in a map c++

本文关键字:C++ 映射      更新时间:2023-10-16

我已经坐了几个小时,试图找到一种在 std::map 中使用复杂值的方法。我的代码是

std::vector<std::complex<double>> coord; // bin coordinates
std::vector<std::string> ref; //A1,D4,...
std::map<std::string,std::complex<double>> bin; //coordinates and reference
std::string letter_ref[] = {"H","G","F","E","D","C","B","A"};
std::string int_ref[] = {"1","2","3","4","5","6","7","8"};
double x=0;
double y=0;
for(int i=0;i<8;++i){
    for(int j=0;j<8;++j){
        coord.push_back(std::complex<double>(7-i,j));
        ref.push_back(letter_ref[i]+int_ref[j]);
        bin.insert(std::pair<std::string,std::complex<double>>(letter_ref[i]+int_ref[j], (7-i,j)));
        //bin.insert(std::pair<std::string,std::complex<double>>(letter_ref[i]+int_ref[j], (7-x,y)));
        ++y;
    }
    ++x;
}

这是构造函数的一部分。我有一个地图和两个应该显示相同事物的向量的原因是因为我开始使用向量,但发现使用起来很痛苦。但我想将旧矢量保留一段时间,以便先获得正确的地图。

但是,地图没有给出预期的结果。打印地图时

std::map<std::string,std::complex<double>>::iterator it;
int i = 0;
for(it=bin.begin();it!=bin.end();++it){
    std::cout<<"["<<it->first<<","<<it->second<<"] ";
    if ((i+1) % 8 == 0)// & i>0)
        std::cout<<"n";
    ++i;
}

在第一种情况下(未注释)是否表明虚部为 0,但第一部分是正确的。第二种情况(注释)仍然显示虚部的 0 值,但实部不是给出值 0-7,而是给出值 0-63。

有谁知道如何在地图中正确使用复数?

在 c'tor 中,您希望在地图中存储一个复数,其中包含实部 7-i 和虚部j。您可以通过传递(7-i, j)来执行此操作,但这不会以您可能期望的方式调用std::complex<double>的c'tor(即使用re=7-iim=j)。

您在代码中实际使用的是逗号运算符。来自维基百科:

在 C 和C++编程语言中,逗号运算符 (由令牌表示)是一个二进制运算符,用于计算其 第一个操作数并丢弃结果,然后计算第二个操作数 操作数并返回此值(和类型)。

因此,通过将(7-i, j)传递给std::complex<double>的c'tor,而不是创建一个具有实部7-i和虚部的虚数j,您可以创建一个具有实部j而没有虚部的复数。所以只需更换您的生产线

bin.insert(std::pair<std::string,std::complex<double>>(letter_ref[i]+int_ref[j], (7-i,j)));

bin.insert(std::pair<std::string,std::complex<double>>(letter_ref[i]+int_ref[j], std::complex<double>(7-i,j)));

使其按预期工作。这会使用您指定的参数显式调用std::complex<double>的 c'tor。