Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/147.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 将2D数组存储到c++;_C++_Arrays_Vector - Fatal编程技术网

C++ 将2D数组存储到c++;

C++ 将2D数组存储到c++;,c++,arrays,vector,C++,Arrays,Vector,假设我有一个如下格式的2D矩阵。第一行表示尺寸标注,其余几行包含图元。在这种情况下,它是一个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 通常,我们可以使用以下方法将矩阵存储在向量中: typedef std::vector<int32_t> vec_1d; typedef std::vector<vec_1d> vec_2d; vec_2d array{

假设我有一个如下格式的2D矩阵。第一行表示尺寸标注,其余几行包含图元。在这种情况下,它是一个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
通常,我们可以使用以下方法将矩阵存储在向量中:

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 }
};
typedef std::vector vec_1d;
typedef std::vec_2d向量;
矢量二维阵列{
{ 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 }
};
<>但是如果我想把上面的数组从文本文件中显示成一个2D向量,就像上面的那个,我将如何在C++中执行这个操作?< /p> ,这应该工作:

#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;
}
#包括“fstream”
#包括“向量”
使用名称空间std;
int main()
{
ifstream fin(“file.txt”);
int n;
fin>>n;
向量<向量>矩阵(n,向量(n));
//或使用typedefs的vec_2d矩阵(n,vec_1d(n))
用于(自动和输入:矩阵)
对于(auto&j:i)
fin>>j;
}