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
|
#include <iostream>
#include <algorithm>
template<int row_count, int col_count>
void dump(int (&arr)[row_count][col_count]) {
std::cout << "[dump]\n\n";
for(int r = 0; row_count > r; ++r) {
for(int c = 0; col_count > c; ++c) {
std::cout << " " << arr[r][c];
}
std::cout << "\n";
}
std::cout << "\n";
}
template<int row_count, int col_count>
void dump_flat(int (&arr)[row_count][col_count]) {
std::cout << "[dump flat]\n\n";
int elem_count = row_count * col_count;
int* p = &arr[0][0];
for(int e = 0; e < elem_count; ++e) {
std::cout << " " << p[e];
}
std::cout << "\n\n";
}
int main() {
int arr[][4] = { {11, 12, 13, 14}
, {21, 22, 23, 24}
, {31, 32, 33, 34} };
const int elem_count = sizeof(arr)/sizeof(arr[0][0]);
const int row_count = sizeof(arr)/sizeof(arr[0]);
const int col_count = elem_count / row_count;
std::cout << "elems = " << elem_count << "\n";
std::cout << "rows = " << row_count << "\n";
std::cout << "cols = " << col_count << "\n";
std::cout << "\n";
dump(arr);
dump_flat(arr);
std::cout << "rotate rows! (take 1 - failed!)\n";
// arr[r] is a pointer to the first row, which is an
// array of 4 ints here, which decays to an int* when passed
// to std::rotate(), so it's the elements of the first row
// that end up rotating rather than the rows.
std::rotate(arr[0], arr[0] + 1, arr[0] + row_count);
std::cout << "\n";
dump(arr);
dump_flat(arr);
std::cout << "rotate back\n";
std::rotate(arr[0], arr[0] + (row_count - 1), arr[0] + row_count);
std::cout << "\n";
dump(arr);
dump_flat(arr);
std::cout << "rotate cols!\n";
for(int r = 0; r < row_count; ++r) {
std::rotate(arr[r], arr[r] + 1, arr[r] + col_count);
}
std::cout << "\n";
dump(arr);
dump_flat(arr);
std::cout << "rotate back!\n";
for(int r = 0; r < row_count; ++r) {
std::rotate(arr[r], arr[r] + (col_count - 1), arr[r] + col_count);
}
std::cout << "\n";
dump(arr);
dump_flat(arr);
std::cout << "rotate rows! (take 2 - works!)\n";
std::rotate(&arr[0], &arr[0] + 1, &arr[0] + row_count);
std::cout << "\n";
dump(arr);
dump_flat(arr);
return 0;
}
|