Apr 25, 2017 at 10:06pm UTC
Can someone show a way to pass a 2D array to a function without knowing both of the dimensions? And explaining why please <3
Apr 25, 2017 at 10:35pm UTC
Array size is part of array type, so to pass it to a function, you have to know the sizes at compile time. E.g. you can pass int[2][2] into a function taking int (&a)[2][2]:
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
void print2x2(const int (&a)[2][2]) {
std::cout << a[0][0] << a[0][1] << '\n'
<< a[1][0] << a[1][1] << '\n' ;
}
int main() {
int a2[2][2] = {{1,2}, {3,4}};
print2x2(a2);
}
demo:
http://coliru.stacked-crooked.com/a/14f8fe1d6675fdfb
To make it possible to call it if you don't know the sizes, you can parametrize that function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
template <class T, std::size_t R, std::size_t C>
void print2D(const T(&a)[R][C]) {
for (const auto & row: a) {
for (const auto & n: row) {
std::cout << n << ' ' ;
}
std::cout << '\n' ;
}
}
int main() {
int a1[2][3] = {{1,2,3}, {4,5,6}};
print2D(a1);
int a2[2][2] = {{1,2}, {3,4}};
print2D(a2);
}
demo
http://coliru.stacked-crooked.com/a/2e519a4515af4a51
If that seems complex, you're right. It's generally much better to use std::array or, if you don't know sizes until run time, std::vector:
1 2 3 4 5 6 7 8 9
void print2D(const std::vector<std::vector<int >>& a) {
// same code
}
int main() {
std::vector<std::vector<int >> a1 = {{1,2,3}, {4,5,6}};
print2D(a1);
std::vector<std::vector<int >> a2 = {{1,2}, {3,4}};
print2D(a2);
}
demo:
http://coliru.stacked-crooked.com/a/56cfee1705c86a09
Last edited on Apr 25, 2017 at 10:42pm UTC