How can I use a complex number as the key in a map? Here is a small example which will not compile:
#include <complex>
#include <map>
int main() {
std::complex<double> zero = 0.0;
std::map<std::complex<double>, int> theMap;
return (theMap.count(zero));
}
I can create the map without errors, but any method (e.g., the count
call above as well as find
, the []
operator, insert
, etc.) generates compile-time errors. It is definitely a problem with my understanding, as I get similar results using clang and g++.
It looks like the compiler cannot compare two complex numbers. I created all of the comparison operators (e.g., bool operator< (const std::complex & lhs, const std::complex & rhs) {return (std::norm(lhs) < std::norm(rhs));}
), which works for comparing complex numbers (as long as you don't mind 3 < -5
being true, which should be fine for map
), but the compiler doesn't pick it up.
I have similar problems with unordered_map (there is no hash for complex<double>
)