【问题标题】:std:: list (doubly linked list) unknown runtime error [closed]std::list(双向链表)未知的运行时错误[关闭]
【发布时间】:2018-09-12 07:54:37
【问题描述】:

我在对我的链表进行操作时遇到问题。我过去能够做到这一点,但无法弄清楚为什么我会收到运行时错误,只是说“程序已停止工作,没有任何解释。无论我使用 push_back、insert 还是任何操作,它都会在它出现时出错到那行代码,我不知道为什么。这只是显示用于这个特定部分的代码。

#include <iostream>
#include <string>
#include <list>

int main() {
    ttree* tree;
    tree = new ttree(); //ttree object
    tree->insert("a string");//insert a string that has been read in
    // passes to ttree insert method
}

class ttree
{
private:
    tnode* _tnodes;  // pointer to _tnodes
    int _maxDepth;  // max depth allowance
    int _currentDepth; // the depth of current node ( root is depth 1)
}

ttree::ttree() //default ttree constructor
{
    _maxDepth = 5;
    _currentDepth = 1;
    _tnodes = new tnode[26];//create Array of 26 tnodes (A-Z)
    //calls tnode constructor
}

void ttree::insert(string key) {
    int index = key[_currentDepth - 1] - 'A';
    (_tnodes)[index].insert(key, _currentDepth);// passes to tnode insert method
}

class tnode
{
private:
    ttree* _nextLevel;  // pointer to the ttree at the next level
    list<string>* _words;  // store keywords
}

tnode::tnode()
{
    _nextLevel = NULL;
    _words = NULL;
}

bool tnode::insert(string key, int level)
{
    cout << key;
    _words->push_back(key);// no matter what I do with the linked list here
    //it errors out right here
    return true;
}

【问题讨论】:

  • 请修复代码。我们需要能够将其剪切并粘贴到 IDE 编辑器中,编译并按原样运行。见minimal reproducible example
  • 我正要发布错误消息,但它们的长度为 4284 字节。
  • edit你的问题告诉我们你做了什么样的调试。我希望您已经在 Valgrind 或类似的检查器中运行了您的minimal reproducible example,并使用诸如 GDB 之类的调试器进行了调查。确保您也启用了全套编译器警告。这些工具告诉了你什么,它们缺少什么信息?并阅读 Eric Lippert 的 How to debug small programs

标签: c++ string list nodes std


【解决方案1】:

_words 是指向std::list 的指针。你在构造函数中将它设置为NULL,而不是其他任何东西。它看起来不需要是指针,只需将其直接作为tnode 的成员即可。

【讨论】:

  • 你是说我应该去掉这里的指针吗?列表* _words;
  • 必须设置成指针
  • 如果确实需要,则构造一个并将其分配到那里而不是NULL。喜欢_words = new std::list();
  • @snipshow7 “必须”为什么?
  • 项目的一部分
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-16
  • 1970-01-01
  • 2011-04-16
相关资源
最近更新 更多