【问题标题】:How can I insert my class objects into my non-STL List?如何将我的类对象插入到我的非 STL 列表中?
【发布时间】: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

标签: c++ list


【解决方案1】:

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

如果 p->prev 为 NULL,此行将崩溃。

【讨论】:

    【解决方案2】:

    使用笔和纸为您的指针操作绘制箭头。

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

    【讨论】:

    • 唯一真正的问题是行:“adjList[0].push_back(adjNode(2, 15));”我知道它成功创建了 adjNode,因为我可以在 cout 语句中引用数据。在创建我的列表时,我或多或少感到困惑(或遗漏了一些东西)(我可以在它之后使用 [numRoads] 吗?),正如其他用户所提到的,我不认为我正在分配内存。
    • Node 构造函数是什么样的?如果它不能以某种方式复制x,那么一旦adjNode 超出范围,您就会崩溃。
    • 结构节点 { 对象数据;节点 *prev;节点 *next; Node(const Object & d = Object(), Node * p = NULL, Node * n = NULL) : data(d), prev(p), next(n) { } };
    • @Brian 初始化列表的头部是什么?如果 Node.prev 默认为 null,并且您没有对列表的头部进行任何其他操作,则第一次插入 p->prev 时将为 null,并且当您设置 p->prev->next
    • @Pete:看起来好像它没有初始化为任何东西。我将如何正确地声明我想要一个包含我可以引用的 adjList 对象的列表?我这样做是希望我可以将此邻接列表用于我的 Dijkstra 算法。
    猜你喜欢
    • 2013-11-21
    • 2020-11-22
    • 1970-01-01
    • 2018-06-19
    • 1970-01-01
    • 2023-02-04
    • 2023-03-20
    • 1970-01-01
    • 2013-07-02
    相关资源
    最近更新 更多