我正在尝试用C ++创建自定义Graph数据结构。我正在使用std :: set来跟踪顶点。我插入一个新顶点时检查该集合,以确保它不在图表中。我使用C ++的经验很少,所以我无法正确实现这一点。问题似乎与contains
函数有关。以下是图表的代码:
#include <iostream>
#include <vector>
#include <list>
#include <map>
#include <set>
#ifndef GRAPH_H
#define GRAPH_H
/*
Graph - Templated graph class
*/
template <typename T>
struct AdjListNode {
T data;
int index;
struct AdjListNode<T> *next;
};
template <typename T>
struct AdjList {
struct AdjListNode<T> *head;
};
template <class T>
class Graph {
private:
std::vector< AdjList<T>* > m_adj_list; //Adjacency list
std::set<T> m_node_set;
std::map<T, int> m_index_map;
int m_num_vertices;
bool m_is_directed;
void addDirectedEdge(T src, T dest);
bool contains(T vertex);
public:
Graph(bool isDirected=true);
bool isDirected();
int numVertices();
bool addVertex(T vertex);
void addEdge(T src, T dest);
std::string printGraph();
AdjListNode<T>* getAdjacent(T vertex);
};
#endif
CPP文件:
#include <iostream>
#include <vector>
#include <list>
#include <set>
#include "Graph.h"
template <class T>
Graph<T>::Graph(bool is_directed) {
m_num_vertices = 0;
m_is_directed = is_directed;
}
template <class T>
bool Graph<T>::isDirected() {
return m_is_directed;
}
template <class T>
int Graph<T>::numVertices() {
return m_num_vertices;
}
template <class T>
bool Graph<T>::addVertex(T vertex) {
//check to make sure node is not in graph
if (contains(vertex)) { //segfault occurs here
AdjListNode<T> *newNode = new AdjListNode<T>;
newNode->index = m_adj_list.size();
AdjList<T> *newAdjList = new AdjList<T>;
newAdjList->head = newNode;
m_adj_list.push_back(newAdjList);
m_num_vertices++;
return true;
} else {
return false;
}
}
template <class T>
void Graph<T>::addDirectedEdge(T src, T dest) {
if (contains(src)) {
AdjListNode<T> *newNode = new AdjListNode<T>;
newNode->data = dest;
newNode->next = NULL;
AdjList<T> *list = m_adj_list[m_index_map[src]];
AdjList<T> *currentNode = list->head;
while (currentNode->next != NULL) {
currentNode = currentNode->next;
}
//insert at the end of adjacency list
currentNode->next = newNode;
}
}
template <class T>
bool Graph<T>::contains(T vertex) {
return m_node_set.find(vertex) == vertex;
}
template <class T>
void Graph<T>::addEdge(T src, T dest) {
addDirectedEdge(src, dest);
if (!m_is_directed) {
addDirectedEdge(dest, src);
}
}
template <class T>
std::string Graph<T>::printGraph() {
return "";
}
template <class T>
AdjListNode<T>* Graph<T>::getAdjacent(T vertex) {
if (*m_node_set.find(vertex) == vertex) {
AdjListNode<T>* list = m_adj_list[m_index_map[vertex]];
return list->head->next;
} else {
return NULL;
}
}
有人能指出我正确的方向来解决这个问题吗?感谢。
答案 0 :(得分:1)
在contains
方法中,不应该是
return (m_node_set.find(vertex) != m_node_set.end());