i was trying to copy two dimensional array to another array with another size. For example: first array with 4 rows and 4 columns:
1 2 3 4
5 6 7 8
9 0 1 2
3 4 5 6
second array with 2 rows and 8 columns:
1 2 3 4 5 6 7 8
9 0 1 2 3 4 5 6
and if there are in the new array more elements than first one then the function will fill it with 0
this is the function i made, but the problem with indexes. How to write it in the right way?
void changearr(int **ppm, int size1, int size2, int size_1, int size_2)
{
int **temp = new int*[size_1];
for (int i = 0; i < size_1; i++)
temp[i] = new int[size_2];
int z = 0;
for (int i = 0; i < size_1; i++, z++)
{
for (int j = 0, k = 0; j < size_2; j++, k++)
{
if (i < size_1 || j < size_2)
{
temp[i][j] = ppm[z][k];
}
else
temp[i][j] = 0
}
}
Create an array to which you want to store the existing array with the same length. A 2d array is an array of one dimensional arrays therefore, to copy (or, to perform any operation on) the elements of the 2d array you need two loops one nested within the other.
A simple solution is to use the clone() method to clone a 2-dimensional array in Java. The following solution uses a for loop to iterate over each row of the original array and then calls the clone() method to copy each row.
Answer: There are different methods to copy an array. You can use a for loop and copy elements of one to another one by one. Use the clone method to clone an array. Use arraycopy() method of System class.
Ohhhhh, what a nice programming puzzle. My solution is to flatten both arrays and copy them.
template <typename T>
static constexpr T* begin(T& value) noexcept
{
return &value;
}
template <typename T, ::std::size_t N>
static constexpr typename ::std::remove_all_extents<T>::type*
begin(T (&array)[N]) noexcept
{
return begin(*array);
}
template <typename T>
static constexpr T* end(T& value) noexcept
{
return &value + 1;
}
template <typename T, ::std::size_t N>
static constexpr typename ::std::remove_all_extents<T>::type*
end(T (&array)[N]) noexcept
{
return end(array[N - 1]);
}
int a[4][4];
int b[2][8];
::std::copy(begin(a), end(a), begin(b));
Why not to make a temporary linear array from the input matrix and then use that to fill the output matrix:
void changearr ( int** ppm, int old_row, int old_col, int new_row, int new_col )
{
int* temp_linear = new int[old_row * old_col];
int k = 0;
for ( int i = 0; i < old_row; i++ )
{
for ( int j = 0; j < old_col; j++ )
{
temp_linear[k++] = ppm[i][j];
}
}
int** temp = new int* [new_row];
for ( int i = 0; i < new_row; i++ )
{
temp[i] = new int[new_col];
}
k = 0;
for ( int i = 0; i < new_row; i++ )
{
for ( int j = 0; j < new_col; j++ )
{
if ( k < old_row * old_col )
{
temp[i][j] = temp_linear[k++];
}
else
{
temp[i][j] = 0;
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With