简体   繁体   English

C ++输出2D矢量

[英]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. 我写了两个for循环,并期望看看它们是否会输出一个名为data的向量中的每个值,但它不起作用。 There is an error relating to data[i].at(j) that I don't quite understand. 有关data[i].at(j)的错误我不太明白。

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. data.at(i).at(j)有错误。

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. 当您在位置i处索引矢量时,您将获得其第i个数字。 That is of type int . 那是int类型。

Then you ask for a method named at() on an int . 然后在int上请求一个以at()命名的方法。 This is not provided by the primitive type int . 原始类型int不提供此功能。

If you are trying to emulate a 2D vector with a 1D, then you could do this: 如果您尝试使用1D模拟2D矢量,那么您可以这样做:

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: 假设我们有一个名为matrix的2D Vector,它包含5乘5的值:

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,3,4,

1, 2, 1,2,

1, 2, 3, 1,2,3,

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

1 1

However, it will then require user input. 但是,它将需要用户输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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