mardi 28 avril 2015

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

This is my 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;

    for ( int j : n )
    {
        cout << setw(7) << j << setw(13) << n[ j ] << endl;
    }
}

It produced this output:

Element        Value
      2            6
      4           10
      6  -1078585116
      8  -1217581056
     10            0

While I expected this output:

Element        Value
      1            2
      2            4
      3            6
      4            8
      5           10

I've tried changing small things, but they didn't work. Where did I do wrong?

Aucun commentaire:

Enregistrer un commentaire