简体   繁体   English

如何以矩阵形式打印我的 2D 矢量? C++

[英]How can I print my 2D vector in a matrix form? C++

I have created a 2D vector that is populated by values in a text file.我创建了一个由文本文件中的值填充的 2D 矢量。 The values provided will always be N*N so my question is, how can I print out the vector of vectors in a matrix form, ie in a 3x3 grid.提供的值将始终为 N*N,所以我的问题是,如何以矩阵形式(即在 3x3 网格中)打印出向量的向量。 My code so far is as follows:到目前为止,我的代码如下:

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int main()
{
    //Declaration
    string line;
    ifstream myfile("example.txt");
    int n;
    int x;
    myfile >> n;

    //Creation of 2D vector
    vector<vector<int> > grid;
    for(int i = 0; i < n; i++){
        vector<int> temp;
        for(int j = 0; j < n; j++){
            while (myfile >> x){
                temp.push_back(x);
            }
        }
        grid.push_back(temp);
    }

    //Display the elements of the 2D vector

    for (int i=0; i<grid.size(); i++){
        for (int j = 0; j<grid[i].size(); j++){
            cout << "[" << grid[i][j] << "]";
        }
    }
    return 0;
}

As you can see I tried to add cout << "[" << grid[i][j] << "]";如您所见,我尝试添加 cout << "[" << grid[i][j] << "]"; to do this but this only outputs a single line of all the values, any help would be much appreciated!要做到这一点,但这只会输出一行所有值,任何帮助将不胜感激!

Put a new line after every loop through i ?在通过i每个循环后放一个新行?

for (int i=0; i<grid.size(); i++) {
    for (int j = 0; j<grid[i].size(); j++) {
        cout << "[" << grid[i][j] << "]";
    }
    // Add a new line after every row
    cout << endl;
}

So I managed to figure it out with the help of @John as he had mentioned the number of vectors I had.所以我在@John 的帮助下设法弄清楚了,因为他提到了我拥有的向量数量。 I didn't consider that I may have just populated the first vector (j=0) with the values rather than having 3 in j=0,1,2.我没有考虑到我可能只是用这些值填充了第一个向量 (j=0) 而不是在 j=0,1,2 中填充了 3。 In the end I used the code:最后我使用了代码:

for (int i=0; i<grid.size(); i++){
    for (int j = 0; j<grid[i].size(); j++){
        cout << "[" << grid[i][j] << "] ";
        if((j+1)%n == 0){
            cout << endl;
        }
    }
}

This displayed it as I had requested but I had the underlying problem as they were all in 1 sub-vector.这按照我的要求显示了它,但我遇到了潜在的问题,因为它们都在 1 个子向量中。 This was simply fixed by changing the:这只是通过更改以下内容来解决的:

while (myfile >> x) { ... }

To:到:

if (myfile >> x) { ... }

Hope this can help some of you!希望这可以帮助你们中的一些人!

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

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