簡體   English   中英

cpp中最簡單的Graph實現

[英]Easiest implementation of Graph in cpp

目前我正在學習graph實現。 我找到了 2 個實現,即在 cpp 中使用vectormatrixadjacency list 但我面臨的問題如下

帶矩陣

  • 傳遞給 function 很難
  • 無法添加新節點
  • memory 效率低下

鄰接表的向量實現

// Code taken from geeksforgeeks
vector<int> adj[V]; 

// adding edge from u to v
adj[u].push_back(v);
  • 無法添加新節點
  • 並且也很難傳遞給 function

所以我想要一個可以解決以上兩個問題的cpp解決方案。

我在cpp中有效且最簡單地實現了graph 它解決了你上面提到的所有問題。 它被稱為vector in vector

// Suppose at start we have
// number of nodes
int nodes = 5;

// number of edges
int edges = 4;

// define graph
vector<vector<int>> graph(nodes, vector<int>());

int u, v; // edge from u -> v
for(int i=0;i<edges;i++){
    cin >> u >> v;
    graph[u].push_back(v);
}

// suppose we want to add node
graph.push_back(vector<int>());

// print graph content
int index = 0;
for(auto x : graph){
    cout << index << "-> ";
    for(auto y: x){
        cout << y << " ";
    }
    cout << endl;
    index ++;
}

輸入上述代碼

5 4
0 1
0 2
2 1
2 3

Output

0-> 1 2 
1-> 
2-> 1 3 
3-> 
4-> 
5-> // new node

優點

  • 可以在運行時添加節點
  • memory高效
  • 您可以像法線向量一樣輕松傳遞給 function
  • 您可以在另一個 function 中找到節點而不通過它。

這絕不是有效的實現,但也許一組對是您正在尋找的。

#include <iostream>
#include <utility>
#include <set>
#include <algorithm>

template<class T>
class graph
{
public:
    std::set<std::pair<T, T>> storage;

    /* true item added, false otherwise */
    bool add_edge(T v1, T v2)
    {
        auto ret = storage.insert(std::make_pair(v1, v2));
        return ret.second;
    }

    /* return value: edges deleted */
    int delete_edge(T v1, T v2)
    {
        return storage.erase(std::make_pair(v1, v2));
    }

    void print_graph()
    {
        std::for_each(storage.begin(), storage.end(),
        [](std::pair<T, T> const& p) {
            std::cout << p.first << "--> " << p.second << std::endl;
        });
    }
};

#include <iostream>
#include "graph.h"

int main()
{
    graph<int> g;
    g.add_edge(5, 4);
    g.add_edge(5, 4);
    g.add_edge(6, 2);
    g.print_graph();
    g.delete_edge(5, 4);
    g.print_graph();
    return 0;
}

編譯命令

g++ -std=c++17 -Wall -Wextra -pedantic main.cpp

Output

5 --> 4
6 --> 2
/* Deleted 5 --> 4 */
6 --> 2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM