-1

Consider this piece of code:

struct MY_VECTOR : public vector<vector<int>> 
{
    int n = this->size();
    int m = (*this)[0].size(); //<== fixed   this[0].size()
    int at(int i, int j)
    {
        if (i < 0 || j < 0 || i >= n || j >= m)
            return 0;
        else
            return (*this)[i][j];
    }
};

I want to access elements but without throwing any exceptions. (I could have done operator[] overloading but it doesn't matter for me now.) Firstly, I have never tried to inherit from STL containers so I'm not even sure If it's ok to do that. (I have read already that's generally a bad idea, but at least I want to give it a try). Secondly I'm not even sure if everything will work correctly, cause as I said already I have never tried to do such things. So I tried to create MY_VECTOR object and call it's constructor.

struct MY_VECTOR : public vector<vector<int>>
{
    int n = this->size();
    int m = (*this)[0].size();
    int at(int i, int j)
    {
        if (i < 0 || j < 0 || i >= n || j >= m)
            return 0;
        else
            return (*this)[i][j];
    }
};

int main()
{
    int n;
    cin >> n;
    MY_VECTOR a(n, vector<int>(n));
}

And it doesn't compile and I don't understand why. Doesn't vector<vector<int>> constructor must be inherited? Or there is a different problem, which I don't see?

Compiler error: "Error E0289: No instance of constructor "MY_VECTOR::MY_VECTOR" matches the argument list"

Learpcs
  • 282
  • 3
  • 10
  • 5
    Highly related: https://stackoverflow.com/questions/6806173/subclass-inherit-standard-containers – πάντα ῥεῖ Nov 25 '21 at 08:36
  • 1
    the answer for the title is: Don't. If you want to know why the code does not compile you should include the compiler error in the question – 463035818_is_not_an_ai Nov 25 '21 at 08:45
  • `this[0].size()` should be `(*this)[0].size()` but you don't check for emptiness. And it cannot be done for member initialization anyway. – Jarod42 Nov 25 '21 at 08:45
  • As others noted before, STL templates were not made to be inherited from. If you want to write a matrix template, I suggest you Google the work done by others, e.g. Stroustrup's template https://www.stroustrup.com/Programming/Matrix/Matrix.h, and the suggested Multidimensional subscript operator for C++23, see http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p2128r6.pdf – Uri Raz Nov 25 '21 at 11:00

1 Answers1

0

I think what you want isn't to inherit from STL but instead make a new class that has a member variable of vector<vector>. Like one of the comments say it's inadvisable to inherit from an STL container.