开发者

How can I insert my class objects into my non-STL List?

I have been working on this assignment for a while now and am quite stuck with inserting into my non-STL list. The code will compile successfully, but segfaults every time it goes to insert into my list. Below is some relevant code.

tripper.h:

class adjNode
{
  public:
    int vertex;
    int weight;
    ad开发者_Go百科jNode(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 ) );
}

Node

 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 ) 
   {
   } 
 };


return iterator( p->prev = p->prev->next = new Node( x, p->prev, p ) );

This line will crash if p->prev is NULL.


Use pen and paper and draw arrows for your pointer ops.

Separate the ops on different lines to be able to express your intent and debug the code more easily.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜