Home > Enterprise >  Adding a member to std::vector<std::vector<int>> class in C
Adding a member to std::vector<std::vector<int>> class in C

Time:11-25

I have to modify a code so that I can add a member to 2D vectors. The code started with a typedef vector<vector<int>> Matrix which I replaced with a Matrix class. I tried to inherit from vector<vector<int>> using :

class Matrix: public vector<vector<int>> {
public:
    int myMember;
};

This way I practically don't have to modify the source code much. However, if I try to run :

Matrix mymatrix (4);

It raises an error :

modele.cpp:19:20: error: no matching function for call to 'Matrix::Matrix(int)'
  Matrix mymatrix (4);
                    ^
In file included from modele.cpp:8:0:
modele.h:6:7: note: candidate: Matrix::Matrix()
 class Matrix: public vector<vector<int>> {
       ^
modele.h:6:7: note:   candidate expects 0 arguments, 1 provided

CodePudding user response:

Constructors are not inherited by default, but can use them in your derived class for that you have to do something like this:

#include <vector>
#include <iostream>
class Matrix : public std::vector<std::vector<int>>{
    public:
        using vector::vector;
        int myMember;
};

int main(){
    Matrix data(1);
    std::vector row = {1,2,3,4,5};
    data.push_back(row);


    for(auto i: data){
        for(auto r : i){
            std::cout << r << std::endl;
        }
    }
}

This way compiler will know all the constructors from the base class. And will call the appropriate constructor for your derived class.

  • Related