Reputation: 81
So I want to create a 2D array in C++ and enter input to it.
int** arr = new int*[arrrows];
I have written a function that allows me to enter input to a 1D array.
void fillintarray(int* arr, int arrsize)
{
for(int i = 0; i < arrrows; i++)
{
std::cin >> arr[i];
}
}
Now I tried to create a function to enter input to a 2D array using the 1D function
void fill2dintarray(int** arr, int arrrows, int arrcols)
{
for(int i = 0; i < arrrows; i++)
{
arr[i] = new int[arrcols];
fillintarray(arr[i], arrcols);
}
}
So would this implementation work correctly? Also, it would be helpful if you could tell me some more good ways to enter input into a 2D array; I'm new to C++. Thanks!
Upvotes: 0
Views: 73
Reputation: 4289
First of all, I would recommend you use vector
instead of handling raw pointers yourself. A 2D array with 5 rows can be represented as std::vector<std::vector<int> > arr(5)
. Then you just need to populate each row by pushing the input into it.
e.g.
void fill2dintarray(std::vector<std::vector<int> > &arr, int arrrows, int arrcols)
{
for(int i = 0; i < arrrows; i++)
{
for (int j = 0; j < arrcols; j++)
{
int temp;
std::cin >> temp;
arr[i].push_back(temp);
}
}
}
int arrrows = 5;
int arrcols = 5;
std::vector<std::vector<int> > arr(arrrows);
fill2dintarray(arr, arrrows, arrcols);
Or, if your input is already in the form of 2D array such as
1 2 3
4 5 6
7 8 9
you can consider reading a whole line as string, turn the string into stringstream, and use empty space as delimiter to feed each value to each row of your 2D array. You can see this Quora answer for inspiration.
Upvotes: 2