简体   繁体   English

将二维数组存储到 C++ 中的二维向量中

[英]storing a 2D array into a 2D vector in c++

Suppose I have a following 2D matrix in the following format.假设我有以下格式的二维矩阵。 First line indicates the dimension and the rest other lines contains the elements.第一行表示维度,其余行包含元素。 In this case it's a 6*6 Matrix:在这种情况下,它是一个 6*6 矩阵:

6
1 2 3 4 2 3
3 3 4 5 2 1
4 3 3 1 2 3
5 4 3 6 2 1
3 2 4 3 4 3
2 3 4 1 5 6

Normally we can store the matrix in a vector using this:通常我们可以使用以下方法将矩阵存储在向量中:

typedef std::vector<int32_t> vec_1d;
typedef std::vector<vec_1d> vec_2d;
vec_2d array{
{ 1, 2, 3, 4, 2, 3 }
, { 3, 3, 4, 5, 2, 1 }
, { 4, 3, 3, 1, 2, 3 }
, { 5, 4, 3, 6, 2, 1 }
, { 3, 2, 4, 3, 4, 3 }
, { 2, 3, 4, 1, 5, 6 }
};

But if I want to take this array in the format I have shown above from a text file into a 2d vector like the above one, how will I do this in c++ ?但是,如果我想将上面显示的格式的这个数组从文本文件转换为像上面那样的二维向量,我将如何在 c++ 中做到这一点?

This should work:这应该有效:

#include "fstream"
#include "vector"
using namespace std;

int main()
{
    ifstream fin("file.txt");
    int n;
    fin >> n;
    vector < vector <int> > matrix (n, vector <int>(n)); 
    // or vec_2d matrix (n, vec_1d(n)); with your typedefs

    for (auto &i: matrix)
        for (auto &j: i)
            fin >> j;
}

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

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