如何将我的类对象插入到非STL列表中?

时间:2010-11-13 23:26:04

标签: c++ list

我现在已经在这个任务上工作了一段时间,而且我很难插入到我的非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 ) 
   {
   } 
 };

2 个答案:

答案 0 :(得分:1)

返回迭代器(p-&gt; prev = p-&gt; prev-&gt; next = new Node(x,p-&gt; prev,p));

如果p-&gt; prev为NULL,则该行将崩溃。

答案 1 :(得分:0)

使用笔和纸,并为指针操作绘制箭头。

将不同行上的操作分开,以便能够表达您的意图并更轻松地调试代码。