简体   繁体   中英

how to initialize a 2D array inside a class while creating and object of it

I have a class with private pointer to pointer (double pointer), which I am using to create a 2D array.

class Arr2D{
    int **arr;
    public:
        Arr2D(int row, int col){
            arr = new int*[r];
            for(int i = 0; i < row; ++i){
                arr[i] = new int[col];
            }
        }
}

I want to initialize this array while creating an object of it as below

int main(){
    Arr2D obj(2,2) = { {1,2}, {3,4} };
} 

how can I initialize the array as show above.

You can use List Initialization to do that. Consider that you wont be creating a matrix but a list of lists of integers. But you can handle it as a matrix if you want. Take a look at this code:

# include <iostream>
# include <initializer_list>
# include <vector>

using namespace std;

class Arr2D {
private:
    vector<vector<int>> Arr;

public:
    Arr2D(initializer_list<vector<int>> p) {
        this->Arr = p;
    }

    void Print () {
        for (int i = 0; i < this->Arr.size (); i++) {
            cout << "row " << i << ": [";

            for (int j = 0; j < this->Arr.at (i).size (); j++) {
                cout << this->Arr.at(i).at (j) << " ";
            }

            cout << "]" << endl;
        }
    }
};

int main(int argc, char *argv[]) {
    Arr2D obj {{1, 2, 3}, {4, 5, 6}};

    obj.Print();

    return 0;
}

the output is:

row 0: [1 2 3 ]
row 1: [4 5 6 ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM