Network C++表示网络结构

对于社交网络分析, 有时需要保存一个完整的网络结构。

需要利用数据结构 图

这里提供一个数据结构范例,可以较快速进行图的操作。


class Vertex
{
public:
	Vertex(void){
		num_in_edges = 0; //这个点的入度
		num_out_edges = 0; //点的出度
	};
	~Vertex(void){};
	vector< pair<int, double> > in_edges; //进入点的index和权重
	vector< pair<int, double> > out_edges; 
	int num_in_edges, num_out_edges;
};
class Graph
{
public:
	Graph(void);
	~Graph(void);


	// Number of vertices
	int vertex_num;
	// Number of edges
	int edge_num;
<span style="white-space:pre">	unordered_map<int, int> vertex_map;</span>
	// Adjacent List
	vector<class Vertex> vertices;
	void add_vertex(int id){
		vertex_map[id] = vertex_num;
		vertices.push_back(class Vertex());
		vertex_num++;
	}
	void add_edge(int from, int to, double weight){
		if (vertex_map.find(from) == vertex_map.end()){
			add_vertex(from);
		}
		if (vertex_map.find(to) == vertex_map.end()){
			add_vertex(to);
		}

		int from_id = vertex_map.find(from)->second;
		int to_id = vertex_map.find(to)->second;

		// if this edge already exists, return
		for (unsigned int i = 0; i < vertices[from_id].out_edges.size(); i++){
			if (vertices[from_id].out_edges[i].first == to_id){
				return;
			}
		}

		vertices[from_id].out_edges.push_back(make_pair(to_id, weight));
		vertices[from_id].num_out_edges++;
		vertices[to_id].in_edges.push_back(make_pair(from_id, weight));
		vertices[to_id].num_in_edges++;
		edge_num++;
	}

 
 



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值