Home > Net >  How to initialize a 2d Vector with different sizes for the row and the column in C ?
How to initialize a 2d Vector with different sizes for the row and the column in C ?

Time:12-16

I don't know why I can't find a clear cut answer to this, as in Java this is straight forward and easy. I am writing a function where the inputs are two different strings and I am creating a double array (or in C a vector) where I define the size of the rows and columns.

In Java, this is easy, all you have to do is:

int myFunction(String text1, String text2) {

  int[][] arr = new int[text1.size()   1][text2.size()   1];

  ...

}

But in C , I am having a hard time doing that with a 2D vector. I did this:

int myFunction(string text1, string text2) {

 vector<vector<int>> arr(text1.size()   1, text2.size()   1);

 ...

}

I know since I am not supposed to pass that in the second parameter for the vector initialization, I just don't know what to do. I get this error:

Line 5: Char 29: error: no matching constructor for initialization of 'vector<vector>' vector<vector> temp(text1.size() 1, text2.size() 1);

Can someone explain how to initialize a 2D vector with defined sizes in C please ? Thanks !

CodePudding user response:

The second argument of the std::vector constructor is the default type.

Here you pass the default type for your rows, so vector<int>(text2.size() 1):

vector<vector<int>> arr(text1.size()   1, vector<int>(text2.size()   1));

Read here why you using namespace std; is considered bad practise.

  • Related