您的位置:首页 > 理论基础 > 计算机网络

Network C++表示网络结构

2015-09-16 14:41 447 查看
对于社交网络分析, 有时需要保存一个完整的网络结构。

需要利用数据结构 图

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

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++;
}




                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: