简体   繁体   中英

C++ output 2D Vector

I wrote two for loops and expected to see if they would output every value in a vector called data , but it doesn't work. There is an error relating to data[i].at(j) that I don't quite understand.

vector<int> data; //it is filled with some integers with x rows and y columns

for ( int i = 0; i < data.size(); ++i) {
    for ( int j = 0; j < col; ++j ) {
        cout << data[i].at(j) << ' ';
    }

    cout << endl;
}

I've also tried this method, but it doesn't work either. data.at(i).at(j) has an error.

for ( int i = 0; i < data.size(); ++i ) {
    for ( int j = 0; j < col; ++j ) {
        cout << data.at(i).at(j) << ' ';
    cout << endl;
}

Can either of these work with a minor fix or don't they work at all?

Focus here:

data[i].at(j) 

When you index your vector at position i , you get the i -th number of it. That is of type int .

Then you ask for a method named at() on an int . This is not provided by the primitive type int .

If you are trying to emulate a 2D vector with a 1D, then you could do this:

for (int i = 0; i < data.size(); ++i)
{
    for (int j = 0; j < col; ++j)
        cout << data[i + j * col] << ' ';
    cout << endl;
}

I find it easier by printing the contents of a 2D Vector exactly like a 2D Array.

Example:

Let's say that we had a 2D Vector called matrix and it contained 5 by 5 values:

1, 2, 3, 4, 5,
1, 2, 3, 4, 5,
1, 2, 3, 4, 5,
1, 2, 3, 4, 5,
1, 2, 3, 4, 5

We need to output the matrix, so we would use:

// The matrix:
vector <vector <int> > matrix ;

// The Row container:
vector <int> row

// The creation of the row:
for (int i = 1 ; i <= 5 ; i = i + 1) {
    row.push_back (i) ;
}

// The creation of the matrix.
for (int j = 1 ; j <= 5 ; j = j + 1) {
    matrix.push_back (row) ;
}

// Print the matrix
for (int k = 0 ; k < matrix.size () ; k = k + 1) {
    for (int l = 0 ; l < matrix [k].size () ; l = l + 1) {
        cout << matrix [k] [l] << ' ' ;
    }

    cout << endl ;
}

The above example will also work if you have rows with different sizes:

1, 2, 3, 4,

1, 2,

1, 2, 3,

1, 2, 3, 4, 5

1

However, it will then require user input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM