c++ - How can I use C++11's range-based for loop to output data in a table? -


this code:

#include <iostream> #include <iomanip> #include <array> using namespace std;  int main() {     // array< int, 5 > n;     int n [ 5 ] = { 2, 4, 6, 8, 10};      cout << "element" << setw(13) << "value" << endl;      ( int j : n )     {         cout << setw(7) << j << setw(13) << n[ j ] << endl;     } } 

it produced output:

element        value       2            6       4           10       6  -1078585116       8  -1217581056      10            0 

while expected output:

element        value       1            2       2            4       3            6       4            8       5           10 

i've tried changing small things, didn't work. did wrong?

if need index when better use ordinary loop instead of range based loop. example

int main() {     // array< int, 5 > n;     int n [ 5 ] = { 2, 4, 6, 8, 10};      cout << "element" << setw(13) << "value" << endl;      ( size_t = 0; < sizeof( n ) / sizeof( *n ); i++ )     {         cout << setw(7) << + 1 << setw(13) << n[ ] << endl;     } } 

if want use range based loop need declare auxiliary count before loop. example

int main() {     // array< int, 5 > n;     int n [ 5 ] = { 2, 4, 6, 8, 10};      cout << "element" << setw(13) << "value" << endl;      size_t = 0;      ( int : n )     {         cout << setw(7) << ++i << setw(13) << << endl;     } } 

as code using elements of array indices in it

for ( int j : n ) {     cout << setw(7) << j << setw(13) << n[ j ] << endl;                       ^^^                ^^^^^                      element of n       using element of n index } 

Comments

Popular posts from this blog

java - Spring Data JPA: Why findOne(id) executing delete query internally? -

python - Mongodb How to add addtional information when aggregating? -

java - Incorrect order of records in M-M relationship in hibernate -