Error using range-based for loop - Eclipse CDT Luna

511 Views Asked by At

I am a beginner at C++ programming. I tried to write a very simple program that combines the use of templates, passing arrays as arguments to a function and a range-based for loop. This is the program that I wrote and compiled using the Eclipse Luna CDT software.

#include <iostream>
using namespace std;

template <typename T>
void display (T myArray[])
{
    int i = 1;
    for (T c : myArray)
    {
        cout << i << " element is " << c << endl;
        ++i;
    }
}

int main()
{
    int numArray[] {1, 2, 3};
    char charArray[] {'a', 'b', 'c'};

    display<int>(numArray);
    display<char>(charArray);

    return 0;
}

But when I save this file and build it, it says that there are errors on line 8, highlighting the range-based for loop. The compiler specifically states that " 'begin' and 'end' was not declared in this scope". The compiler is mingw-w64 and has been setup for C++11. How do I resolve this error?

Thank you for your answers.

2

There are 2 best solutions below

3
On BEST ANSWER

To use a range based for loop you'll need to use std::array instead of C-style array. I modified your code so it works. Note that you'll need to pass -std=c++11 flag to the compiler.

#include <array>
#include <iostream>
using namespace std;

template <typename T>
void display (T myArray)
{
    int i = 1;
    for (auto c : myArray)
    {
        cout << i << " element is " << c << endl;
        ++i;
    }
}

int main()
{
    std::array<int, 3> numArray {1, 2, 3};
    std::array<char, 3> charArray {'a', 'b', 'c'};

    display(numArray);
    display(charArray);

    return 0;
}
4
On

in c++ there is no "for each" like in other languages as php etc...

so you have to tell the function where the array ends, because if you give an array to the function, it only gets an pointer of the starting postition...

this should work for you:

    #include <iostream>
using namespace std;

template <typename T>
void display (T myArray[], int arraysize)
{
    for (int i = 0; i < arraysize ;i++)
    {
        cout << i+1 << " element is " << myArray[i] << endl;
    }
}

int main()
{
    int numArray[] = {1, 2, 3};
    char charArray[] = {'a', 'b', 'c'};

    display<int>(numArray, 3);
    display<char>(charArray, 3);

    return 0;