对称矩阵的C++容器和==运算符

C++ container and == operator for symmetric matrix

本文关键字:运算符 C++ 对称      更新时间:2023-10-16

以下是我处理对称矩阵的部分代码:

SymmetricMatrix<std::deque<int> > a(3);
SymmetricMatrix<std::list<int> > b(3);
SymmetricMatrix<std::vector<int> > c(4);
SymmetricMatrix<std::list<int> > d(3);
a(1,1) = b(1,1) = c(1,1) = d(1,1) = 7;
a(1,2) = b(2,1) = c(1,2) = d(2,2) = 3;
if(b == c) {}

您建议使用哪种容器或数据结构来实现SymmetricMatrix类?(我尝试过std::vector)此外,我如何实现==运算符?现在,它适用于b==d,但不适用于a==b(no match for 'operator ==')。

==a == b上未定义的原因是因为类SymmetricMatrix<std::deque<int> >SymmetricMatrix<std::list<int> >的类型不同。其中一个内部定义的运算符==将不适用。

然而,C++允许您定义"独立的"操作员模板,如以下所示:

template <typename T, typename U>
bool operator==(const SymmetricMatrix<T>& lhs, const SymmetricMatrix<U>& rhs) {
    // Do the comparison here
}

此运算符引用具有不同类型参数的SymmetricMatrix对象,因此编译器将能够为a == b调用它。您可能需要在SymmetricMatrix模板中向该运算符声明"友谊",以便该运算符访问矩阵类的私有和受保护成员。