Jul 17, 2019 at 4:07pm Jul 17, 2019 at 4:07pm UTC
Hi,
I'm not understanding why my dynamic array won't compile.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
int square = 1;
int k;
for (int i = length; i < length*length; i++){
for (int j = 1; j < length*length; j++){
if (i / j == j){
square = i;
k = j;
break ;
}
}
if (square != 1){
break ;
}
}
string* arr;
arr = new string[k][k];
I'm trying to get better working with dynamic arrays, but I'm at a roadblock with this.
Thank you.
***edit***
Also, if anyone has a better way of finding the smallest square root greater than number n than a loop with not one, but two forbidden breaks, I'd welcome a better solution.
*********
Last edited on Jul 17, 2019 at 5:53pm Jul 17, 2019 at 5:53pm UTC
Jul 17, 2019 at 4:45pm Jul 17, 2019 at 4:45pm UTC
Maybe something like this:
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
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
template <typename T>
T** make_2d_array(size_t rows, size_t columns)
{
auto a = new T*[rows]; // array of row pointers
a[0] = new T[rows * columns]; // all T data as a single block
for (size_t i = 1; i < rows; ++i) // init row pointers
a[i] = a[i - 1] + columns;
return a;
}
int main()
{
size_t length = 0;
std::cout << "Length: " ;
std::cin >> length;
double sqr = std::ceil(std::sqrt(length));
length = size_t(sqr * sqr);
auto a = make_2d_array<std::string>(length, length);
for (size_t r = 0; r < length; ++r)
for (size_t c = 0; c < length; ++c)
a[r][c] = std::to_string(r) + ':' + std::to_string(c);
for (size_t r = 0; r < length; ++r) {
for (size_t c = 0; c < length; ++c)
std::cout << std::setw(5) << a[r][c] << ' ' ;
std::cout << '\n' ;
}
delete [] a[0]; // delete data block
delete [] a; // delete row pointers
}
Last edited on Jul 17, 2019 at 4:46pm Jul 17, 2019 at 4:46pm UTC
Jul 17, 2019 at 10:52pm Jul 17, 2019 at 10:52pm UTC
Do all dynamic 2d arrays have to be an array of templated objects?
Jul 17, 2019 at 11:09pm Jul 17, 2019 at 11:09pm UTC
Nope.
Last edited on Jul 17, 2019 at 11:12pm Jul 17, 2019 at 11:12pm UTC