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);
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]));
printArray can now also be used with std::vector<T> :
std::vector<int> vec;
Nawaz source share