Reputation: 1825
I am relatively new to C++ programming and I wanted to learn more about language by programming matrices. I have this code that works, but I can't figure out how to create code that would work for any amount of columns and rows. I have trouble passing matrices to functions, which have rows and columns determined by user input.
This is what I have:
#include <iostream>
using namespace std;
template <int rows, int cols>
void display(int (&array)[rows][cols]) {
int i, j;
cout<<"\n";
for(i = 0; i<rows; i++) {
for(j = 0; j<cols; j++) {
cout<<" ";
cout<<array[i][j];
}
cout<<"\n";
}
}
int main() {
int M1[3][3];
cout<<"Enter your matrix elements: \n";
int i, j;
for(i = 0; i<3; i++) {
for(j = 0; j<3; j++) {
cout<<"a["<<i<<"]["<<j<<"]: ";
cin>>M1[i][j];
}
}
display(M1);
return 0;
}
Is performing such task possible without complicating the code too much?
Upvotes: 1
Views: 42996
Reputation: 165
Many remarks and comments are okay, but I think that the best strategy is to use a single vector for storage and a vector for the shape. Learn on pythons numpy to understand the concept or search for ndarray, which is how many different platforms name this concept (n dimensional array). A class bundling the data vector, the shape vector and convenient operators and member functions is then the way to go.
Upvotes: 1
Reputation: 1649
The classical answer would have required you to perform dynamic memory allocations for you array. This is a bit overwhelming especially if you are a newbie. (And to the best of my knowledge this is still way to do it in C)
However the recommend way to do something like that in modern C++ is to use the Standard Template Library.
/*
... Stuff where you get input from the user, specifically the num of rows and cols
... Say these vals were stored in 2 ints num_rows and num_cols
*/
std::vector<std::vector<int> > mat(num_rows);
for (int i = 0; i < num_rows; i++) {
mat[i].resize(num_cols); // this will allow you to now just use [][] to access stuff
}
Please see the first comment below, it has a nice way to avoid the loop to set up the vector and takes care of it at initialization time
Upvotes: 1