chenhao jin
chenhao jin

Reputation: 3

How to define a nested class and use it

I declared a nested class Element, and I want to use create such object and push into an array that storing Element in my AOSMatrix class. The problem I have is that I don't know what should I use in the function push_back in my

void push_back(int i, int j, double val) 

Here is the rest of my code: #include #include

using namespace std;

class AOSMatrix {
    public:
    AOSMatrix(int M, int N) : iRows(M), jCols(N) {}

    void push_back(int i, int j, double val) {
        assert(i < iRows && i >= 0);
        assert(j < jCols && j >= 0);

        arrayData.push_back(???);
    }

    private:
        class Element {
            public:
                int row, col;
                double val;
        }

        int iRows, jCols;
        vector<Element> arrayData;
}

Upvotes: 0

Views: 52

Answers (1)

Saurabh Shirodkar
Saurabh Shirodkar

Reputation: 334

Your class Element should have a constructor to initialize the fields as:

class Element{
    public:
        int row, col;
        double val;
        Element(int row, int col, double val){
            this->row = row;
            this->col = col;
            this->val = val;
        }
}

And you can push back an element in your vector as:

Element e(i, j, val);
arrayData.push_back(e);

Upvotes: 1

Related Questions