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.
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.