Reputation: 315
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?
Upvotes: 4
Views: 4452
Reputation: 73366
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;
}
Upvotes: 4
Reputation: 959
I find it easier by printing the contents of a 2D Vector exactly like a 2D Array.
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.
Upvotes: 0