Home > Software design >  How to use vector as a private member in class to store and pass data
How to use vector as a private member in class to store and pass data

Time:12-13

Assuming that there is a Class called Solution:

class Solution{
private:
    int COL;
    int ROW;

    vector<vector <int>> grid(ROW, vector<int>(COL));
public:
    void setData();
};

Then put the definition of function setData()

void Solution::setData(){
    for (int i = 0; i < ROW; i  ){
        for (int j = 0; j < COL; j  ){
            grid[i][j] = 1;
        }
    }
}
  • Firstly, in the declaration of vector grid, ROW and COL is unread;
  • Secondly, if I revise the declaration of grid as vector<vector<int>> grid(100, vector<int>(100))(namely, define dimension of vector clearly), it then lose the feature of dynamic
  • Last, if I revise the declaration of vector grid, the programme would be interrupted when running setData()

Sincerely thank you for any suggestions!

thanks for you guys, I defined the constructor function:

Solution(){
    ROW = 100;
    COL = 100;
}

however, COL and ROW is also unreadable in definition of grid(vector<vector>)

thank you!

CodePudding user response:

Currently your definition of grid

vector<vector <int>> grid(ROW, vector<int>(COL));

looks rather like a function. State it's type and name, and initialise elsewhere to avoid this:

class Solution {
private:
    const int COL;
    const int ROW;

    vector<vector <int>> grid;
public:
    void setData();

    Solution() :
        ROW{ 10 },
        COL {5 },
        grid(ROW, vector<int>(COL))
    {}
};

I made the sizes const, cos they are for the lifetime of your Solution, I presume.

You can change the constructor to take the values for the row and column and pass them in, rather than use the magic number I chose.

CodePudding user response:

In your code ROW and COL are undefined and you try to use them in your function setData().

Try using simple functions to add data

AddRow(vecotr<int> rowValue) {
     grid.push_back(rowValue);
}

If you want to use a Set function you have to check validity.

SetRow(uint pos, vecotr<int> rowValue){
     if (pos<=grid.size())
          return;
     ...
}

CodePudding user response:

As you can fill the vector at the running time so let's change the setData function like:

class Solution{
private:
    int COL;
    int ROW;
    vector<vector <int>> grid;

public:
    void setData();

    Solution(int c, int r){
        COL = c;
        ROW = r;
    }
};

void Solution::setData(){
    vector <int> row;
    row.reserve(COL);
    for (int j = 0; j < COL; j  ){
        row.push_back(1);
    }
    for (int i = 0; i < ROW; i  ){
        grid.push_back(x);
    }
}

int main()
{
    Solution x(5,10);
    x.setData();
    return 0;
}

I tested it and it worked properly. If you don't want to put 1 for all items in your grid, change the first for loop as you desired and make them two nested loops in your setData function.

  • Related