【发布时间】:2010-11-13 23:26:04
【问题描述】:
我已经从事这项任务有一段时间了,并且非常坚持插入我的非 STL 列表。该代码将成功编译,但每次插入我的列表时都会出现段错误。下面是一些相关的代码。
tripper.h:
class adjNode
{
public:
int vertex;
int weight;
adjNode(int v, int w) : vertex(v), weight(w) { }
adjNode() { }
};
tripper.cpp:
Tripper::Tripper(Road *roads, int numRoads, int size)
{
List <adjNode> adjList[numRoads];
for (int i=0; i<numRoads; i++) //Doesn't work with either line
{
adjList[roads[i].city1].push_back(adjNode(roads[i].city2, roads[i].distance));
//adjList[0].push_back(adjNode(2, 15)); //Really it's nothing but 3 integers involved
}
for (int i=0; i<9; i++)
{
for (List<adjNode>::iterator itr = adjList[i].begin(); itr != adjList[i].end(); itr++)
{
cout << "There is an edge going from " << i << " to " << (*itr).vertex;
cout << " with a weight of " << (*itr).weight << endl;
}
}
} // Tripper()
list.h:
void push_back( const Object & x )
{
insert( end( ), x );
}
iterator insert( iterator itr, const Object & x )
{
Node *p = itr.current;
theSize++;
return iterator( p->prev = p->prev->next = new Node( x, p->prev, p ) );
}
节点
struct Node {
Object data;
Node *prev;
Node *next;
Node( const Object & d = Object( ), Node * p = NULL, Node * n = NULL )
: data( d ), prev( p ), next( n )
{
}
};
【问题讨论】:
-
您遇到了段错误,我在该代码中没有看到内存分配的证据。我猜是有联系的。
-
在第一个 for 循环中添加 'assert (roads[i].city1