简体   繁体   中英

Constructor for wrapper around std::vector

I'm trying to write a wrapper class with a data member std::vector. How should my class's default constructor look like so that I can do the following without getting out of range error:

Wrapper W;
W[0] = value;  //overloaded index operator, forwards to the vector

The default constructor is irrelevant. Your operator [] needs to check whether the supplied index is out of range and make the vector bigger as necessary. (I'm assuming here that "returns reference to the vector<T> " is a typo and you want to forward to the vector's operator[] at some point).

You have to resize the vector before accessing the element:

// in the class definition
std::vector vec;

T &operator[](typename std::vector<T>::size_type idx)
{
    if (idx >= vec.size()) {
        vec.resize(idx + 1);
    }

    return vec[idx];
}

Edit: now 0 instead of i , that's a huge typo. In that case, you can just construct a vector of size 1 in-place:

std::vector<T> vec = std::vector<T>(1);

public:
T &operator[](typename std::vector<T>::size_type idx)
{
    return vec[idx];
}

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