如何在映射 C++ 中使用复数
How to use complex numbers in a map c++
我已经坐了几个小时,试图找到一种在 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-i
和im=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。
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 将函数类成员映射到类本身内部
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 使用std::函数映射对象方法
- 如何加载(或映射)文件部分的最大大小,但适合在Windows上的RAM
- C++映射分割错误(核心转储)
- 内联映射初始化的动态atexit析构函数崩溃
- 使用"std::unordereded_map"映射到"std::list"对象
- 如何从多映射中删除特定的重复项
- 在未初始化映射的情况下,将值插入到映射的映射中
- QT通过C++添加映射QML项目
- 在c++中访问int到类对象的映射时出错
- 在C++中搜索嵌套多映射值
- 错误处理.将系统错误代码映射到泛型
- C++匿名结构作为std::映射值
- 如何从存储在std::映射中的std::集中删除元素
- 递归无序映射
- 正在VS调试器中监视映射条目