向 std::vector<T> 添加运算符
adding an operator to std::vector<T>
我正在尝试向 std::vector 添加一个运算符来识别 2 个向量何时大致相同。我该怎么做?
template<typename T> //only numeric types
class ImperciseVector: public std::vector<T> {
public:
ImperciseVector() {} //is this constructor needed?
bool operator~ (const ImperciseVector& v) {
T l1sq=0.0, l2sq=0.0, l3sq=0.0;
if ((*this).size() != v.size() || (*this).size==0 || v.size()==0) return false;
for (int j = 0; j<(*this).size(); j++) {
l1sq += (*this)[j]*(*this)[j];
l2sq += v[j]*v[j];
l3sq+= ((*this)[j]-v[j])*((*this)[j]-v[j]);
}
//some estimate such that length of their their difference (relative to their size) is small enough
if (l3sq/(l1sq*l2sq) <= 0.00001) return true;
return false;
}
};
它不起作用,甚至在我写运算符时都无法识别什么是 ment。如何正确或更好地做到这一点?
operator~()
是一个 一元 运算符。它的用法只能是~iv
,不能是iv1 ~ iv2
。在这种情况下,最好简单地编写一个名为 approx()
或重载 operator==
的成员函数(确实有意义,对吧?两个 ImpreciseVector
相等,如果它们是大约相等?)
旁注,ImpreciseVector<T>
没有继承自 vector<T>
。请改用组合。
我正在尝试向 std::vector 添加一个运算符来识别 2 个向量何时大致相同。我该怎么做?
template<typename T> //only numeric types
class ImperciseVector: public std::vector<T> {
public:
ImperciseVector() {} //is this constructor needed?
bool operator~ (const ImperciseVector& v) {
T l1sq=0.0, l2sq=0.0, l3sq=0.0;
if ((*this).size() != v.size() || (*this).size==0 || v.size()==0) return false;
for (int j = 0; j<(*this).size(); j++) {
l1sq += (*this)[j]*(*this)[j];
l2sq += v[j]*v[j];
l3sq+= ((*this)[j]-v[j])*((*this)[j]-v[j]);
}
//some estimate such that length of their their difference (relative to their size) is small enough
if (l3sq/(l1sq*l2sq) <= 0.00001) return true;
return false;
}
};
它不起作用,甚至在我写运算符时都无法识别什么是 ment。如何正确或更好地做到这一点?
operator~()
是一个 一元 运算符。它的用法只能是~iv
,不能是iv1 ~ iv2
。在这种情况下,最好简单地编写一个名为 approx()
或重载 operator==
的成员函数(确实有意义,对吧?两个 ImpreciseVector
相等,如果它们是大约相等?)
旁注,ImpreciseVector<T>
没有继承自 vector<T>
。请改用组合。