2

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.

10
  • 1
    And what exactly is happening with your current code? Commented Sep 22, 2018 at 20:27
  • @OmidCompSCI I am getting this error: expected ‘,’ or ‘;’ before ‘=’ Commented Sep 22, 2018 at 20:30
  • 1
    A int** is no 2d array. One of the most important properties of an array is that its elements are continuous in memory. What you're trying to do here is a no-no. Use one dimension and calculate a linear index from x and y indices. Commented Sep 22, 2018 at 20:31
  • 1
    Is there a reason you can't just use std::vector? Commented Sep 22, 2018 at 20:37
  • 1
    @Abhishek take a look at zcrou.com/blog/dev/nested-initializers Commented Sep 22, 2018 at 20:46

1 Answer 1

1

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 ]
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.