Reputation: 149
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.
Upvotes: 2
Views: 62
Reputation: 331
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 ]
Upvotes: 1