使用Stl的C ++中的邻接图

时间:2018-11-26 08:26:40

标签: c++ stl

我想使用vector并在将vector声明为全局变量的情况下使图的邻接列表表示,其中将内存分配给堆栈或堆中的向量

    #include<bits/stdc++.h>
    #include<vector>
    using namespace std;


    void addedge(vector<int> &graph, int u, int v) {
        graph[u].push_back(v);
        graph[v].push_back(u);
    }

    void printgraph(const vector<int> &gph) {
        for (int v = 0 : gph) {
            cout << v;
            for (auto x : gph[v]) {
                cout << x;
                printf("\n");
            }
        }
    }

    int main() {
        vector<int> gph;
        addedge(gph, 2, 3);
        addedge(gph, 6, 7);
        addedge(gph, 1, 2);
        printgraph(gph);

    }

2 个答案:

答案 0 :(得分:3)

gphvector中的int,因此您无法访问push_back中的方法graph[u],因为graph[u]是{{1} }!

您可以将邻接列表想象成int的节省空间的矩阵(2D),其中可以有不同大小的行。 但最终它是2D结构。 这意味着您必须将邻接列表声明为int

以下代码应为您提供有关其工作方式的指示:

vector<vector<int>>

答案 1 :(得分:0)

您可以将数据和行为收集到一个类中,而不是在邻接列表中使用显式参数。根据图形的稀疏程度,可以使用各种表示形式。为了与Davide's answer形成对比,我将使用std::multimap<int, int>

class Graph
{
    std::multimap<int, int> edges;
public:
    void addedge(int u, int v)
    {
        edges.insert(u, v);
        edges.insert(v, u);
    }

    friend std::ostream& operator<<(std::ostream& os, const Graph & graph)
    {
        for (auto v_it = graph.begin(), v_end = {}; v_it != graph.end(); v_it = v_end)
        {
            v_end = graph.upper_bound(v_it->first);
            os << v_it->first << " : ";
            for (auto it = v_it; it != v_end; ++it)
            {
                os << it->second << " ";
            }
            os << std::endl;
        }
        return os;
    }
}

int main() {
    Graph gph;

    gph.addedge(2, 3);
    gph.addedge(6, 7);
    gph.addedge(1, 2);
    std::cout << graph;
}