I know I can have any type in for loop to iterate over:
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
int ar[] ={ 1, 2, 3 };
for (int i:ar)
{
cout << i << endl;
}
}
But I could not have an pointer type:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char const *argv[])
{
for (char *p:argv) //or better char const *p
// using auto keyword expands to error-type in vscode
{
ifstream in(p);
}
return 0;
}
will give:
error: ‘begin’ was not declared in this scope
for (char *p:argv)
error: ‘end’ was not declared in this scope
for (char *p:argv)
^~~~
So I am assuming, the syntax of c++ for loop (auto var : vector/array)
is not the same as c
-style, old-fashion loop for(int i=0; i<size; i++)
? Because I am required (in case of using c++ style for loop) to provided a structure with valid iterator (thus the errors, looking for begin() and end() iterators. But then why did the first case works? The first case, an array with ints, is also a structure without any kind of iterators, but old pointers (to access). So why the first is okay, but the second isn't?