I was trying to print a 2D array using for_each and range based for loop.
My program goes like this:-
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};
//for_each (begin(a), end(a), [] (int x) { cout<<x<<" ";}); this code throws error
for_each (begin(a[0]), end(a[2]), [] (int x) { cout<<x<<" ";}); //this code works well, why ?
cout<<endl;
for (auto &row: a) // without & for row, error is thrown
{
for (auto x:row) // no & needed for x, why ?
{
cout<<x<<" ";
}
}
return 0;
}
Why did my first for_each throw errors and why is & symbol necessary for row? What is its type? Is row a pointer?
Aucun commentaire:
Enregistrer un commentaire