dimanche 30 août 2015

passing array to a function and using it in for-range loop [duplicate]

This question already has an answer here:

I am learning c++ so question might be stupid but I haven't managed to solve it hence my first SO question :) So I have the following code

# include <iostream>

using namespace std;

void printArr(int Arr[])
{
    for (auto i : Arr)
        cout << i << ", ";
}

int main()
{
    int myArr[] = {28,1,0,55,12,54,22};
    for (auto i : myArr)
        cout << i << ", ";
    // printArr(myArr);
}

The code doesn't compile at the moment. So if you comment out the for range loop the code will compile. The problem is in iterator because compiler says that there is no begin() or end() defined in the scope of the function, but curious thing is that it works in the main() body i.e. just remove function printArr() and it will compile and for range loop will work. I think the problem is in the fact that array is passed as pointer (at least that is how I understand compiler error).

So is there any was to pass array and use for range loop?

I have solved the problem in two ways for now but I am still curious about why it doesn't work because I am basically doing a work around and not understanding what is happening.
First way with <vector>

# include <iostream>
# include <vector>

using namespace std;

void printArr(vector<int> Arr)
{
    cout << "Print func" << endl;
    for (auto i : Arr)
        cout << i << ", ";
}

int main()
{
    vector<int> myArr = {28,1,0,55,12,54,22};
    cout << "Main func" << endl;
    for (auto &i : myArr)
        cout << i << ", ";
    cout << endl;
    printArr(myArr);
}

And by using auto

# include <iostream>
# include <vector>
# include <typeinfo>

using namespace std;

void printArr(auto Arr)
{
    for (auto i : Arr)
        cout << i << ", ";
    cout << endl << "type in the function: " << typeid(Arr).name();
}

int main()
{
    auto myArr {28,1,0,55,12,54,22};
    cout << "deducted type: " << typeid(myArr).name() << endl;  
    for (auto i : myArr)
        cout << i << ", ";
    printArr(myArr);
}

I would also like to know is this the proper way to use auto?
I use compiler g++ (Ubuntu 4.9.2-10ubuntu13) 4.9.2 with -std=c++14.

Aucun commentaire:

Enregistrer un commentaire