简体   繁体   中英

C++: Operator [] overloading for vector<>

I'm currently trying to overload the operator [] on vectors. I'm trying to get this operator to work as in Matlab or Python for negative indexes or indexes greater than the vector's length. My problem isn't to get the right result, but to actually overload the operator, knowing I will use the non-overloaded operator in the overloading code. I need it for vectors of a specific class but it would be even better if it worked for any vector .

Right now my code is: header:

MyClass std::vector::operator[](std::vector<MyClass> const vector,int const idx) const;

source:

Myclass vector::operator[](vector<MyClass> const vector,int const idx) const {
    n=vector.size()
    if((idx>=0) && (idx<n)){
        return vector[idx];
    }
    else if(idx<0){
        return vector[n+idx%n]
    }
    else{
        return vector[idx%n]
    }
}

And I get the errors:

error: 'template<class _Tp, class _Alloc> class std::vector' used without template parameters
error: non-member function 'MyClass operator[](std::vector<MyClass>, int)' cannot have cv-qualifier
error: 'MyClass operator[](std::vector<MyClass>, int)' must be a nonstatic member function

I'm sorry if this problem has already been discussed, but I couldn't find it... Thank you very much in advance for your answers !

Your error is about the syntax:

vector::operator[]

should be

vector<MyClass>::operator[]

However, you cannot arbitrarily redefine operators of classes that you do not own. What you can do is create your own MyVector class that publicly inherits from vector :

struct MyVector : std::vector<MyClass>
{
    MyClass& operator[](std::size_t index)
    { 
        // ...
    } 
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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