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
|
// I have a function that removes a pointer form array of pointers and rotate
// other pointer for one place left.
// Now if size of array is n and pointers on positions array[n-1] and
// array[n-2] are the same (because i have rotated array to fill a gap)
// how can i delete only pointer on position n-1;
#include <chrono>
#include <exception>
#include <iostream>
#include <random>
#include <string>
void printPtop(const int* const * const ptop, int rows, int* cols);
void removeRow(int** ptop, int k, int& rows, int* cols);
int main()
{
// Just to avoid magic numbers in short example code:
constexpr int M_Rows { 5 };
constexpr int M_Cols { 7 };
int** ptop = new int*[M_Rows];
// I assume class "Token" uses some sort of indexes like these:
int ptop_rows { M_Rows };
int* ptop_cols = new int[M_Cols] {};
// Let's fill our 2D container with random data to test it:
std::mt19937 eng ( std::chrono::high_resolution_clock::now()
.time_since_epoch().count() );
std::uniform_int_distribution<> dst(1, M_Cols);
for(int i { 0 }; i < M_Rows; ++i) {
int cols { dst(eng) };
ptop[i] = new int[cols];
ptop_cols[i] = cols;
for(int j { 0 }; j < ptop_cols[i]; ++j) {
std::uniform_int_distribution dst(1, 9);
ptop[i][j] = dst(eng);
}
}
// Let's see what's inside:
std::cout << "Original 2D container:\n";
printPtop(ptop, ptop_rows, ptop_cols);
// Now let's remove second row:
try {
removeRow(ptop, 1, ptop_rows, ptop_cols); // erase the entire II row
std::cout << "\n2D container after second row has been erased:\n";
printPtop(ptop, ptop_rows, ptop_cols);
} catch (std::out_of_range& e) {
std::cout << "Erasion failed: " << e.what() << '\n';
}
}
void printPtop(const int* const * const ptop, int rows, int* cols)
{
for(int i { 0 }; i < rows; ++i) {
for(int j { 0 }; j < cols[i]; ++j) {
std::cout << ptop[i][j];
}
std::cout << '\n';
}
}
void removeRow(int** ptop, int k, int& rows, int* cols)
{
if(k >= rows) {
throw std::out_of_range(
std::string("Cannot delete beyond "
+ std::to_string(rows - 1))
);
}
delete ptop[k];
for (int i { k }; i < rows - 1; ++i) {
ptop[i] = ptop[i + 1];
cols[i] = cols[i + 1];
}
ptop[rows - 1] = nullptr;
cols[rows - 1] = 0;
--rows;
}
|