首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >cpp中图的最简单实现

问cpp中图的最简单实现
EN

Stack Overflow用户
提问于 2020-05-24 12:59:37
回答 2查看 151关注 0票数 3

目前我正在学习graph实现。我在cpp中找到了两个实现,即使用matrix和adjacency list的vector。但我面临的问题是

带矩阵

传递到函数的possible

  • memory

  • 是很难的

  • ,添加新节点并不是

  • 效率低下的

邻接表的向量实现

代码语言:javascript
复制
// Code taken from geeksforgeeks
vector<int> adj[V]; 

// adding edge from u to v
adj[u].push_back(v);

  • 添加新节点是不可能的
  • ,并且传递到函数也是困难的

。

所以我想在cpp中找到一个能解决以上两个问题的解决方案。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-05-24 13:02:36

我有graph在cpp中的高效和最简单的实现。它解决了你上面提到的所有问题。它被称为vector in vector。

代码语言:javascript
复制
// 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 ++;
}

输入上述代码

代码语言:javascript
复制
5 4
0 1
0 2
2 1
2 3

输出

代码语言:javascript
复制
0-> 1 2 
1-> 
2-> 1 3 
3-> 
4-> 
5-> // new node

优势

efficient

  • you
  • 可以在运行时添加节点,
  • 内存可以像法线向量
  • 那样简单地传递到函数中,无需传递就可以在另一个函数中找到节点。
票数 1
EN

Stack Overflow用户

发布于 2020-05-24 14:22:51

这并不是一种高效的实现,但您可能需要一组对。

代码语言:javascript
复制
#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;
        });
    }
};

代码语言:javascript
复制
#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;
}

编译命令

代码语言:javascript
复制
g++ -std=c++17 -Wall -Wextra -pedantic main.cpp

输出

代码语言:javascript
复制
5 --> 4
6 --> 2
/* Deleted 5 --> 4 */
6 --> 2
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61986337

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档