简体   繁体   中英

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
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++ ?

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;
}

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