我需要将阵列样式的邻接矩阵转换为矢量样式(以使其看起来更好)

i need to convert my array styled adjacency matrix into vector styled (to make it look better)

本文关键字:样式 更好 看起来 阵列 转换 邻接矩阵      更新时间:2023-10-16

我是图形概念的新手,我只是想通过编写小型代码并使用它来学习它。我有一个基于2D数组的邻接矩阵无向图类,我想将其转换为2D向量。

我通过执行vector<vector<int>> graphed初始化了一个向量。但是我无法在构造函数中对其进行修改,并且添加((函数也是不可行的。该代码正在给出逻辑错误和崩溃。显示功能只是二进制矩阵的奇特显示。那里的毫无疑问

#include<iostream>
#include<vector>
using namespace std;
class my_graph{
    public:
        vector<vector<int>> graphed;
        int row=0;
        int col=0;
        my_graph(int size){
            int row=size;
            int col=size;
            // what am i supposed to type here to make the graphed 2d vector
            // size equal to the user provided size.
        }
        void add_edge(int i,int j){
            graphed[i][j]=1;//am i supposed to use pushback() function here?
            graphed[j][i]=1; // or is it fine?
        }
        void display(int size){
            cout<<" ";
            for(int i=0;i<size;i++){
                cout<<" "<<i;
            }
            cout<<"n";
            cout<<" ";
            for(int i=0;i<2*size;i++){
                cout<<"-";
            }
            cout<<"n";
            for(int i=0;i<size;i++){
                cout<<i<<"|";
                for(int j=0;j<size;j++){
                    cout<<graphed[i][j]<<" ";
                }
                cout<<"n";
            }
        }
};
int main(){
    int v=6;
    my_graph g1(v);
    g1.add_edge(1,2);
    g1.add_edge(1,4);
    g1.add_edge(1,5);
    g1.add_edge(2,5);
    g1.add_edge(2,3);
    g1.add_edge(3,5);
    g1.add_edge(3,0);
    g1.add_edge(5,4);
    g1.add_edge(0,4);
    g1.add_edge(0,3);
    g1.display(v);
    return 0;
}
my desired output is
  0 1 2 3 4 5
 ------------
0|0 0 0 1 1 0
1|0 0 1 0 1 1
2|0 1 0 1 0 1
3|1 0 1 0 0 1
4|1 1 0 0 0 1
5|0 1 1 1 1 0
thanks for helping.

要初始化 std::vector<std::vector<int>>,您可以执行以下操作:

    my_graph(int size){
        int row=size;
        int col=size;
        graphed = std::vector<std::vector<int>>(size, std::vector<int>(size, 0));
    }

这将把graphed设置为size矢量的向量,每个向量包含size ZEROS。

使用成员初始化列表是常见的做法:

    my_graph(int size)
      : row(size), col(size),
        graphed = std::vector<std::vector<int>>(size, std::vector<int>(size, 0))
    {
    }

除此之外,您的代码不需要更改即可使用std::vector

https://godbolt.org/z/lyctnv