如何在map中使用复数作为key?以下是一个无法编译的小例子:
#include <complex>
#include <map>
int main() {
std::complex<double> zero = 0.0;
std::map<std::complex<double>, int> theMap;
return (theMap.count(zero));
}
我可以创建地图而不出现错误,但任何方法(例如上面的
count
调用以及find
,[]
运算符,insert
等)都会生成编译时错误。这绝对是我的理解问题,因为我使用clang和g++得到类似的结果。看起来编译器无法比较两个复数。我创建了所有比较运算符(例如
bool operator< (const std::complex & lhs, const std::complex & rhs) {return (std::norm(lhs) < std::norm(rhs));}
),这适用于比较复数(只要您不介意3 < -5
是true,对于map
应该没问题),但编译器没有捕捉到它。我在unordered_map中也遇到类似的问题(
complex<double>
没有哈希)。
1 == -1 == i == -i
(以及它们与其他复数相等)吗?你只能插入其中一个到映射表中。当然,每个相等集合都是一样的。 - NPE(lhs.real() < rhs.real()) || (lhs.real() == rhs.real() && lhs.imag() < rhs.imag())
。 - Timothy Shieldsstd::complex
类型没有内置的比较运算符(除了==
和!=
)。 - Timothy Shieldsstd=c++11
,结果出现了operator <
不存在的问题。非常感谢你指出这个问题。真的没有想到。非常感谢! - WhozCraig