[英]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 ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.