I want to create debug template for array for printing array. This is my template
#define debug(x) cerr << #x <<" = "; print(x); cerr << endl;
void print(ll t) {cerr << t;}
void print(int t) {cerr << t;}
void print(float t) {cerr << t;}
void print(string t) {cerr << t;}
void print(char t) {cerr << t;}
template <class T> void print(vector <T> v) {cerr << "[ "; for (T i : v) {print(i); cerr << " ";} cerr << "]";}
template <class T> void print(T arr[]) {cerr << "[ "; for (T i : arr) {print(i); cerr << " ";} cerr << "]";}
But its giving some errors for array but vector works fine,
template <class T> void print(T arr[]) {cerr << "[ "; for (T i : arr) {print(i); cerr << " ";} cerr << "]";}
^~~
A.cpp:16:55: note: suggested alternatives:
In file included from c:\mingw\lib\gcc\mingw32\6.3.0\include\c \mingw32\bits\stdc .h:95:0,
from A.cpp:1:
c:\mingw\lib\gcc\mingw32\6.3.0\include\c \valarray:1206:5: note: 'std::begin'
begin(const valarray<_Tp>& __va)
^~~~~
c:\mingw\lib\gcc\mingw32\6.3.0\include\c \valarray:1206:5: note: 'std::begin'
A.cpp:16:55: error: 'end' was not declared in this scope
template <class T> void print(T arr[]) {cerr << "[ "; for (T i : arr) {print(i); cerr << " ";} cerr << "]";}
^~~
A.cpp:16:55: note: suggested alternatives:
In file included from c:\mingw\lib\gcc\mingw32\6.3.0\include\c \mingw32\bits\stdc .h:95:0,
from A.cpp:1:
c:\mingw\lib\gcc\mingw32\6.3.0\include\c \valarray:1226:5: note: 'std::end'
end(const valarray<_Tp>& __va)
^~~
c:\mingw\lib\gcc\mingw32\6.3.0\include\c \valarray:1226:5: note: 'std::end'
So how to create a debug for array ?
CodePudding user response:
A range-based for loop (for(T i : v)
internally uses std::begin and std::end to determine the range it hast to iterate over. These methods work for arrays whose size is fixed at compile time, e.g. int arr[10];
, for any standard container, like std::vector
, std::list
, or any class that has a .begin()
and .end()
-method that return iterators, I think.
However, it does not work for pointers.
In fact print(T arr[])
equals print(T *arr)
. You can't determine the length of an array, when you only got a pointer. You can't even determine wether or not this pointer is pointing to an array. So you can't use range-based for loops with pointers.
So how to create a debug for array ?
If you want to use dynamically allocated arrays you have to pass the arrays size along
template <class T> void print(T v[], size_t size)
and use a normal for loop
for(size_t i = 0; i < size; i ) { ... }
Another possibility is to make a template for array-size, as in this question: Can someone explain this template code that gives me the size of an array?