如何push_back一个双向数组?

时间:2018-11-08 18:51:35

标签: c++ arrays vector stdvector

#include <iostream>
#include <vector>
#include <utility>

using namespace std;

int main() {
int A[6][6];

for (int i = 0; i < 6; i++){
    for(int j = 0; j <6; j++){
        A[i][j] = 0;
    }
}

A[0][1] = 1;
A[0][3] = 1;
A[1][2] = 1;
A[1][4] = 1;
A[2][4] = 1;
A[3][1] = 1;
A[4][3] = 1;
A[4][5] = 1;
A[5][2] = 1;

vector< vector< int > >;
A[0].push_back(1);
}

我正在尝试从图中创建一个邻接矩阵。我的教授给了我这段代码,但是它有太多错误,而且我从未使用过vector <vector < int > >。编译器给我的错误如下:

26  2 [Error] declaration does not declare anything [-fpermissive]
27  7 [Error] request for member 'push_back' in 'A[0]', which is of non-class type 'int [6]'

1 个答案:

答案 0 :(得分:1)

不能push_back()用于数组(A)。您需要创建一个向量(B)才能使用push_back()

vector < vector < int > > B (6);

for (int i = 0; i < 6; i++){
    for(int j = 0; j <6; j++){
        B[i].push_back(A[i][j]);
    }
}

要打印B

for (int i = 0; i < 6; i++){
    for(int j = 0; j <6; j++){
        std::cout << B[i][j] << ' ';
    }
    std::cout << std::endl;
}

输出:

0 1 0 1 0 0 
0 0 1 0 1 0 
0 0 0 0 1 0 
0 1 0 0 0 0 
0 0 0 1 0 1 
0 0 1 0 0 0