0

I'ld like to manually set the value of a 2D array that is a class member. 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}};

}
4
  • 2
    You can initialize array like that, just when you're declaring the array. Commented Nov 4, 2013 at 11:58
  • That doesn't quite answer my question, could you please clarify? How do I declare the array in my set up that lets me manually fiddle with the values? Commented Nov 4, 2013 at 12:00
  • You can initialize (by assigning) plain array only at the point of declaration. You can only fill the array later by assigning to each element, not by assigning 'to the whole'. This and thousands of other reasons is why you should avoid them at all cost. Commented Nov 4, 2013 at 15:29
  • It's because I happen to have data that's more or less a 20 by 4 table without an entirely convenient pattern to for loop through for each element. Commented Nov 4, 2013 at 17:48

1 Answer 1

1

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:

class SomeClass
{
    vector<vector<int>> myArray;
public:
    void setMyArray()
    {
        myArray.insert(myArray.end(), {{1,2,3},{1,2,3},{1,2,3}});
    }
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.