How can I create a vector with a maximum length?

Viewed 145

I want to create a container that provides all of the same functionality as a std::vector but with the caveat that you cannot add anymore elements once the vector reaches a specified size.

My first thought was to inherit from std::vector and do something like

template <typename T, unsigned int max>
class MyVector : public std::vector<T> {
  public:
    // override push_back, insert, fill constructor, etc...
    // For example:
    virtual void push_back(const T& var) override {
      if (this.size() < max) vec.push_back(var);
    }
};

But then I learned that inheriting STL containers is bad.

Second thought was to create a wrapper class, i.e.

template <typename T, unsigned int max>
class MyVector {
  private:
    std::vector<T> vec;
  public:
    // Wrappers for every single std::vector function...
    iterator begin() { return vec.begin(); }
    const_iterator begin() const { return vec.begin(); }
    //and on and on and on...etc.
};

But this smells bad to me. Seems very difficult to maintain.

Am I missing something obvious, should I try an alternative approach?

1 Answers

How can I create a vector with a maximum length?

You cannot do that with std::vector. You can however refrain from inserting any elements after you reach some limit. For example:

if (v.size() < 10) {
    // OK, we can insert
}

I want to create a container that provides all of the same functionality as a std::vector but with the caveat that you cannot add anymore elements once the vector reaches a specified size.

That, you can do.

virtual void push_back(const T& var) override {

std::vector::push_back isn't virtual, so you may not override it.

Also, I recommend considering whether the push back should be silently ignored in the case max is reached.

But then I learned that inheriting STL containers is bad.

To be more specific, publicly inheriting them is a bit precarious.

Using private inheritance, you can use using to pick the members that you wish to delegate directly, and implement the differing members manually.

Seems very difficult to maintain.

The standard library doesn't change very often, and the vector class hasn't changed much so far, and changes have been quite simple, so "very difficult" is debatable - although subjective of course.

You could use meta-programming to make it maintainable. But that may be bit of an over-engineered approach.

Related