我对C ++很陌生,我对std :: map有疑问。对于学校项目,我必须在地图中存储空心矩阵(仅存储非零元素),因此我必须创建与矩阵中的坐标对应的类IJ。最后,我有这个:
std::map<IJ, std::complex<double>> matrix;
我已经重载了运算符==和运算符&lt;如下:
bool IJ::operator==(const IJ& other) const{
return (this->i == other.getI() && this->j == other.getJ());
}
bool IJ::operator<(const IJ& other) const{
return (this->i < other.getI() || (this->i == other.getI() && this->j < other.getJ()));
}
我检查过:他们工作正常。 但是我在显示地图时遇到了麻烦。我尝试使用find(为了有一个const方法),at(这给了我同样的问题)但它没有工作,并且没有更好的结果与operator []。他们在这里:
// Display using find
for(int i = 1; i <= 3; i++){
for(int j = 1; j <= 3; j++){
if(matrix.find(IJ(i, j)) != matrix.end())
std::cout << (matrix.find(IJ(i, j)))->second << " ";
else
std::cout << "(0.0,0.0) ";
}
std::cout << std::endl;
}
std::cout << std::endl;
// Display using operator[]
for(int i = 1; i <= 3; i++){
for(int j = 1; j <= 3; j++){
std::cout << matrix[IJ(i, j)] << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
以下是发生的事情:
// Tests of the operators :
std::cout << (IJ(1,1) == IJ(1,1)) << std::endl; // 1
std::cout << (IJ(1,1) == IJ(2,1)) << std::endl; // 0
std::cout << (IJ(1,1) < IJ(1,1)) << std::endl; // 0
std::cout << (IJ(1,4) < IJ(1,3)) << std::endl; // 0
std::cout << (IJ(2,2) < IJ(3,1)) << std::endl; // 1
// Filling the matrix and displaying it step by step (operator[] on the left and find on the right)
matrix[IJ(1, 1)] = 1;
/*(1,0) (0,0) (0,0) (0.0,0.0) (0.0,0.0) (0.0,0.0)
(1,0) (0,0) (0,0) (0.0,0.0) (0.0,0.0) (0.0,0.0)
(1,0) (0,0) (0,0) (0.0,0.0) (0.0,0.0) (0.0,0.0) */
matrix[IJ(2, 3)] = 4;
/*(1,0) (0,0) (4,0) (0.0,0.0) (0.0,0.0) (0.0,0.0)
(1,0) (0,0) (4,0) (0.0,0.0) (0.0,0.0) (0.0,0.0)
(1,0) (0,0) (4,0) (0.0,0.0) (0.0,0.0) (0.0,0.0) */
matrix[IJ(3, 3)] = 2;
/*(1,0) (0,0) (2,0) (0.0,0.0) (0.0,0.0) (0.0,0.0)
(1,0) (0,0) (2,0) (0.0,0.0) (0.0,0.0) (0.0,0.0)
(1,0) (0,0) (2,0) (0.0,0.0) (0.0,0.0) (0.0,0.0) */
对于记录,创建IJ ij(1,1);
然后执行matrix[ij] = 1
会得到相同的结果。我猜测运算符[]的问题来自于我的一个愚蠢的错误,但我对find方法感到困惑。我发现了一些其他主题,但问题主要来自使用char *而不是string作为键和来自重载的运算符。非常感谢任何帮助,谢谢!