This succeeds:
#include <iostream>
#include <vector>
using namespace std;
int test(vector<int> items)
{
for (int item : items)
{
cout << item;
}
return 0;
}
int main()
{
vector<int> items = { 1, 2, 3 };
test(items);
return 0;
}
This fails:
#include <iostream>
using namespace std;
int test(int items[])
{
for (int item : items)
{
cout << item;
}
return 0;
}
int main()
{
int items[] = { 1, 2, 3 };
test(items);
return 0;
}
The error message is:
main.cpp: In function ‘int test(int*)’:
main.cpp:14:21: error: ‘begin’ was not declared in this scope
for (int item : items)
^~~~~
main.cpp:14:21: note: suggested alternatives:
In file included from /usr/include/c++/6/string:51:0,
from /usr/include/c++/6/bits/locale_classes.h:40,
from /usr/include/c++/6/bits/ios_base.h:41,
from /usr/include/c++/6/ios:42,
from /usr/include/c++/6/ostream:38,
from /usr/include/c++/6/iostream:39,
from main.cpp:9:
/usr/include/c++/6/bits/range_access.h:87:5: note: ‘std::begin’
begin(_Tp (&__arr)[_Nm])
^~~~~
/usr/include/c++/6/bits/range_access.h:87:5: note: ‘std::begin’
main.cpp:14:21: error: ‘end’ was not declared in this scope
for (int item : items)
^~~~~
main.cpp:14:21: note: suggested alternatives:
In file included from /usr/include/c++/6/string:51:0,
from /usr/include/c++/6/bits/locale_classes.h:40,
from /usr/include/c++/6/bits/ios_base.h:41,
from /usr/include/c++/6/ios:42,
from /usr/include/c++/6/ostream:38,
from /usr/include/c++/6/iostream:39,
from main.cpp:9:
/usr/include/c++/6/bits/range_access.h:97:5: note: ‘std::end’
end(_Tp (&__arr)[_Nm])
^~~
/usr/include/c++/6/bits/range_access.h:97:5: note: ‘std::end’
I found a similar problem, which explained that the program did not know the size of the array. How to fix for each loop in C++?
But when I tested this, it was successful:
#include <iostream>
using namespace std;
int main()
{
int items[] = { 1, 2, 3 };
for (int item : items)
{
cout << item;
}
return 0;
}
Why does this succeed without specifying the size of the array?