Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

while (end of array) - how to recognize

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!

like image 572
Lila Avatar asked Nov 28 '22 04:11

Lila


2 Answers

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

like image 64
Armen Tsirunyan Avatar answered Nov 29 '22 18:11

Armen Tsirunyan


Since you are using C++, a vector<int> and iterators will do you better over the long haul.

like image 21
Daniel A. White Avatar answered Nov 29 '22 18:11

Daniel A. White