So, I completed a project with ease in C++, only to realize I was supposed to write it in Java. This wouldn’t be too big of a deal, except that my code uses multidimensional vectors, like:
vector <vector<int> > arr
Is there something equivalent in Java that would give the same result without having to drastically rewrite the program?
Here’s the code snippet from the C++ program that I am having trouble translating:
vector <vector <int> > arr;
cin >> n;
while (n > 0)
{
vector <int> row;
int u;
for (int i = 0; i < n ; ++i)
{
cin >> u;
row.push_back(u);
}
arr.push_back(row);
n = comb(row.size(), k);
k++;
}
for (int i = 0; i < arr.size(); i+=2)
for (int j = 0; j < arr[i].size(); ++j)
sum += arr[i][j];
for (int i = 1; i < arr.size(); i+=2)
for (int j = 0; j < arr[i].size(); ++j)
diff += arr[i][j];
The
ArrayListshould provide the functionality that you need, if you declare it as anArrayList<ArrayList<Integer>>. Your calls topush_back()are equivalent to calls toadd(). You will lose the array index access notation, but this can be resolved by chaining calls toget().