While (end of array) - how to recognize

I have an array of numbers {1,2,3,4,5} or an array of characters or something else. I want to write a template method to print a full array. It works, there are only some problems. Maybe I will write the code first:

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; } 

Do you see the problem? while(start[i] != 0) is not the best way to read the end of an array;) What do I need for other parameters?

Thanks!

+4
source share
5 answers

Option 1: pass pointer and number of elements

  template<class T> void doSth(T* arr, int size) 

Surface - will work with both dynamic and automatic arrays.
Downside - you need to know the size. You must pass it on.

Option2: parameterize a template with a size that will be automatically displayed

 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

+12
source

Since you are using C ++, vector<int> and iterators will do their best in the long run.

+11
source

If you want to use an array, not a pointer, you can write a function template as:

 template <typename T, size_t N> void printArray(T (&start)[N]) { int i = 0; while ( i < N) { std::cout << start[i] << std::endl; i++; } } int xs1[] = {1,2,3,4,5,6,7}; int xs2[] = {1,0,3,6,7}; printArray(xs1); //okay printArray(xs2); //okay int *start = xs1; printArray(start); //error - cannot pass pointer anymore! 

So the best solution would be: std::vector<T> .

Or it’s even better to use a range (a pair of iterators), which is very idiomatic because:

 template <typename FwdIterator> void printArray(FwdIterator begin, FwdIterator end) { while (begin != end) { std::cout << *begin << std::endl; begin++; } } int xs1[] = {1,2,3,4,5,6,7}; int xs2[] = {1,0,3,6,7}; printArray(xs1, xs1 + sizeof(xs1)/sizeof(xs1[0])); //okay printArray(xs2, xs2 + sizeof(xs2)/sizeof(xs2[0])); //okay int *start = xs1; printArray(start, start + sizeof(xs1)/sizeof(xs1[0])); //okay! 

printArray can now also be used with std::vector<T> :

 std::vector<int> vec; //you can use std::list as well! //populate vec printArray(vec.begin(), vec.end()); 
+6
source

Pass both the address of the array and its length.

+2
source

If you use a compile-time array, you can do this with a template:

 template <typename T, size_t N> static inline void print_array(const T (&a)[N]) { for (size_t i = 0; i < N; ++i) std::cout << a[i] << std::endl; } int main() { int a[] = {1,2}; print_array(a); } 

If you only need to print arrays, also look at the beautiful printer that uses this material internally.

+2
source

All Articles