Hello,
I am new to recursion and was confused on how to add elements to a 2d vector using recursion. I know how to add elements using nested for loops. Lets say I have this loop below:
int teams;
cout<< "Enter the amount of teams" <<endl;
cin >> teams;
for (int i = 0; i < teams+1; i++) {
vector<int> row; // Create an empty row
for (int j = 0; j < teams+1; j++) {
row.push_back((i-1)+j); // Add an element (column) to the row
}
test.push_back(row);
}
for (int i = 1; i < teams+1; i++) {
for (int j = 1; j < teams+1; j++) {
cout << setw(4)<<test[i][j];
}
cout << endl;
}
}
How could I transform this into a recursive block of code?
Thanks in advance.
Your lines 14-19. No.
* Vector indices start from 0, not 1.
* You do assume that the vector 'test' and every vector within it has teams+1 elements. However, a vector knows its size. Use it.
1 2 3 4 5 6
for ( size_t row = 0; row < test.size(); ++row ) {
for ( size_t col = 0; col < test[row].size(); ++col ) {
std::cout << std::setw(4) << test[row][col];
}
std::cout << '\n';
}
Or, with range for syntax:
1 2 3 4 5 6
for ( constauto & row : test ) {
for ( auto elem : row ) {
std::cout << std::setw(4) << elem;
}
std::cout << '\n';
}
By recursion, I mean making this into a function. I know the base case would be when the vector is empty, I have an idea of how the recursive case would work but I cant put it all together. It would be something like: