c++ - for_each & ranged base for on 2D array -
i trying print 2d array using for_each , range based for loop.
my program goes 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<<" ";}); code throws error for_each (begin(a[0]), end(a[2]), [] (int x) { cout<<x<<" ";}); //this code works well, why ? cout<<endl; (auto &row: a) // without & row, error thrown { (auto x:row) // no & needed x, why ? { cout<<x<<" "; } } return 0; } why did first for_each throw errors , why & symbol necessary row? type? row pointer?
for_each (begin(a), end(a), [] (int x) { cout<<x<<" ";}); begin(a) yields int(*)[3] (pointer array of size [3]), , dereferencing yields int(&)[3], while lambda expression expects int argument.
for_each (begin(a[0]), end(a[2]), [] (int x) { cout<<x<<" ";}); begin(a[0]) yields int* points first element in first row of a, , end(a[2]) yields int* pointing 1 past last element in last row of a, works.
now range-based for part.
if remove & line for (auto& row : a) error occurs on following line for(auto x : row). because of way range-based for specified. clause pertinent use case is
if
__rangearray, begin_expr__range, end_expr(__range + __bound),__boundnumber of elements in array (if array has unknown size or of incomplete type, program ill-formed)
hereon i'll referring identifiers mentioned in explanation section of linked page.
consider case for (auto& row : a):
__range deduced int(&)[3][3] (reference array of size [3][3]). __begin deduced int(*)[3] (pointer array of size [3]) because type of __range decays pointer first row of 2d array. range_expression have auto& row, row deduced int(&)[3] (reference array of size [3]).
next, same process repeated inner range-based for. in case, __range int(&)[3] , array clause quoted above applies; remaining type deduction process similar described above.
__range = int(&)[3] __begin = int* x = int now consider case for (auto row : a):
__range, __begin , __end deduced same. crucial difference in case range_expression auto row, causes decay of int(*)[3] type __begin deduced as. means row deduced int *, , none of 3 clauses determination of begin_expr/end_expr described handle raw pointer. results in compilation error within nested for loop.
Comments
Post a Comment