简体   繁体   中英

Inherit from std::vector<T> and overload operator[] for custom indexing

I want to be able to index an std::vector such that when I access data through operator [], index zero is lowerbound and the end of the vector is upperbound.

This is what I am trying to do. Not sure how to do it in C++.

using namespace std;

class Provider
{
    public: string name;
};

template <class T>
class Vec : public std::vector<T>
{
    private Vec(){}
    public Vec(int upperbound, int lowerbound)
    {
        ub = upperbound;
        lb = lowerbound;
    }

    public:
        T& operator[] (int);
    private:
        int ub;
        int lb;
};

//How to do this?
T& VecDQ::operator[] (int idx)
{
    return (ub - lb) + idx;
}


int main()
{
    int upperBound = 175642;
    int lowerBound = 175000;

    // I want a Vec of deques<Provider> index such that idx [0] is starting at lowerbound
    Vec<std::deque<Provider>> vecOfDeq(upperBound, lowerBound);

    //Here, fill the Vec<std::deque<Provider>> with some random examples

    // Here, print out Vec[175000].at(1).name << std::endl; // Vec[175000] is really Vec[0]

    return 0;
}
return *(begin() + lb + idx);

or

return std::vector<T>::operator [](lb+idx);

upperbound is pretty much useless, unless you want to go in loops.

Also, I have to agree with the others, this seems like a bad idea.

There are some typos in your sample code

//How to do this?
T& VecDQ::operator[] (int idx)
{
    return (ub - lb) + idx;
}

Here you are telling the compiler that you are defining the operator[] member function of the VecDQ class. You have not declared a VecDQ class, I'm assuming you meant Vec class. Aside from that, the definition should be inside the class, because you have a templated class, the compiler will not know what "T" is outside of the templated class.

Here's one posible definition:

T& operator[] (int idx)
{
    return this->at(idx - lb);
}

The at member function of the vector class returns a reference to the item at that index. You need to subtract the lower bound from the index given.

You will need to decide whether to resize your base vector dynamically (when a new index is given) or whether to do it when the Vec derived class is constructed.

Here's your program with the change above, with a Vec constructor that pre-allocates the base vector with default-constructed elements. I also supplied a constructor to the Provider class to be able to construct it with either literal character strings or std::string.

http://coliru.stacked-crooked.com/a/40f5267799bc0f11

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