简体   繁体   English

在std :: vector中添加一个运算符<T>

[英]adding an operator to std::vector<T>

I am trying to add an operator to std::vector to identify when 2 vectors are approximately the same. 我正在尝试向std :: vector添加一个运算符,以识别2个向量何时大致相同。 How do I do it? 我该怎么做?

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;
        }
};

It does not work and does not even recognize when I write the operator what is ment. 当我向操作员编写内容时,它不起作用,甚至无法识别。 How to do it correctly or better? 如何正确或更好地做到这一点?

operator~() is a unary operator. operator~()是一元运算符。 It's usage can only be ~iv , not iv1 ~ iv2 . 它的使用只能是~iv ,不iv1 ~ iv2 It'd be better to simply write a member function called something like approx() or overload operator== in this case (in does make sense, right? Two ImpreciseVector s are equal if they're approximately equal?) 在这种情况下,最好只编写一个称为诸如approx()或重载operator==类的成员函数(在某种意义上,对吗?对,如果两个ImpreciseVector大致相等,则它们相等)

Side-note, don't have ImpreciseVector<T> inherit from vector<T> . 旁注,不要有ImpreciseVector<T>vector<T>继承。 Use composition instead. 请改用合成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM