1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
|
#include <cmath>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <numeric>
using rows_cols = std::pair<int, int>;
void displayCStyleArray(const int* const arr, const rows_cols& dims);
int copyCStyleArraysRegion(const int* const from, const rows_cols& f_dims,
const rows_cols& start_el,
int* const to, const rows_cols& t_dims,
const rows_cols& stretch);
int main()
{
// Is this big enough?
constexpr int Max_Rows { 12 };
constexpr int Max_Cols { 10 };
int bigger_arr[Max_Rows * Max_Cols];
std::iota(std::begin(bigger_arr), std::end(bigger_arr), 1);
std::cout << "Bigger array:\n";
displayCStyleArray(bigger_arr, { Max_Rows, Max_Cols } );
rows_cols start_el { 3, 2 }; // 3, 2 --> no meaning, just for test
rows_cols stretch { 4, 5 }; // 4, 5 --> no meaning, just for test
int* smaller_arr = new int [stretch.first * stretch.second] {};
std::cout << "\nSmaller array (before):\n";
displayCStyleArray(smaller_arr, stretch);
int copied {
copyCStyleArraysRegion(bigger_arr, { Max_Rows, Max_Cols },
start_el,
smaller_arr, stretch,
stretch)
};
std::cout << "\nSmaller array after:\n";
displayCStyleArray(smaller_arr, stretch);
std::cout << "\nTotal element copied: " << copied << '\n';
delete smaller_arr;
smaller_arr = nullptr;
}
void displayCStyleArray(const int* const arr, const rows_cols& dims)
{
for (int i {}; i < dims.first; ++i) {
for (int j {}; j < dims.second; ++j) {
std::cout << std::setw(4) << arr[i * dims.second + j];
}
std::cout << '\n';
}
}
int copyCStyleArraysRegion(const int* const from, const rows_cols& f_dims,
const rows_cols& start_el,
int* const to, const rows_cols& t_dims,
const rows_cols& stretch)
{
if ( start_el.first + stretch.first >= f_dims.first
|| start_el.second + stretch.second >= f_dims.second
|| t_dims.first > stretch.first
|| t_dims.second > stretch.second )
{
return 0;
}
int counter {};
const int* start = &from[start_el.first * f_dims.second + start_el.second];
for (int i {}; i < stretch.first; ++i) {
for (int j {}; j < stretch.second; ++j) {
to[i * stretch.second + j] = start[i * f_dims.second + j];
++counter;
}
}
return counter;
}
|