I have an array of numbers {1,2,3,4,5} or an array of chars or whatever. I want to a write a template method to print out the full array. It works, there are just some problems. Maybe i post first the code:
template <typename A>
void printArray(A start) {
int i = 0;
while (start[i] != 0) {
std::cout << start[i] << std::endl;
i++;
}
}
int main(int argc, char **argv) {
using namespace std;
int xs[] = {1,2,3,4,5,6,7}; //works
//int xs[] = {1,0,3,6,7}; of course its not working (because of the 0)
int *start = xs;
printArray(start);
return 0;
}
Can you see the problem? while(start[i] != 0)
is not the best way to read an array to end ;) What do I have for other options?
Thank you!
Option 1: pass a pointer and the number of elements
template<class T>
void doSth(T* arr, int size)
Upside - will work with both dynamic and automatic arrays.
Downside - you must know the size. You must pass it.
Option2: parametrize the template with the size which will be auto-deduced
template <class T, int N>
void doSth(T(&arr)[N])
Downside - Dynamic arrays cannot be passed
Option 3: Be a good programmer and use std::vector
's
Since you are using C++, a vector<int>
and iterators
will do you better over the long haul.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With