简体   繁体   English

使用类成员的指针初始化2D数组?

[英]Initializing a 2D Array using Pointers from a Class Member?

I'ld like to manually set the value of a 2D array that is a class member. 我想手动设置作为类成员的2D数组的值。 Largely because I already fill it up with loops in a different method but in a different method I want to fill it by hand. 很大程度上是因为我已经用不同的方法用循环填充了它,但是我想用另一种方法手工填充它。

class SomeClass {
private:
   int** myArray;
public:
   void setMyArray(int /*h*/,int /*w*/);
}

void SomeClass::setMyArray() {
// Something like this:
this->myArray** = { {1,2,3},{3,2,1},{4,5,6}};

}

Failing that, is there a way to generate its dimensions and then fill manually? 如果失败,是否有一种方法可以生成其尺寸,然后手动填充?

void SomeClass::setMyArray( int height, int width ) {
// Something like this:
this->myArray** = new*int[height];
for ( 0...height, i ) {
    this->myArray[i] = new[width];
}

    myArray** = {{1,2,3},{1,2,3},{1,2,3}};

}

Avoiding bare pointers: 避免裸露的指针:

vector<vector<int>> myArray {{1,2,3},{1,2,3},{1,2,3}};

You can even insert initializer-list later and re-write your class like below: 您甚至可以稍后插入initializer-list并重新编写类,如下所示:

class SomeClass
{
    vector<vector<int>> myArray;
public:
    void setMyArray()
    {
        myArray.insert(myArray.end(), {{1,2,3},{1,2,3},{1,2,3}});
    }
};

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

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