0
/* Copy constructor */
List(const List<value_type>& list)
{
    // for (iterator it = list.begin(); it != list.end(); ++it); 
    //   this->push_back(*it);
    // The commented part above is what I want it to do.
    std::cout << "empty = " << this->empty(); // no seg fault;
    std::cout << "size = " << this->size(); // also causes a seg fault
    this->push_back("string") // causes a seg fault
}

尝试运行此代码会使我的程序出现段错误。似乎每次我试图改变或改变(这个)它只是抛出一个段错误。

它还说(这个)不是空的(这似乎是唯一一个不抛出段错误的)

这是调用更多信息的方法的代码。希望这里有人可以让我对这里发生的事情有所了解。

void insert(iterator position, const value_type& in)
{
    // If inserting at the front, just change the head to a new Node
    if (position == this->head) 
        this->head = new Node<value_type>(in);
    else
    {
        Node<value_type>* node = this->head;
        // iterate to the position of "position".
        for (; node->next != position.node; node = node->next);
        node->next = new Node<value_type>(in);
    }
    // This is here to put back all the old data into it's correct position.
    // I was having way too much with keeping the integrity of the data
    // while inserting into the middle of the list, so I created this little hack.
    for (iterator it = position; it != this->end(); ++it)
    {
            Node<value_type> *node = this->head;
            for (; node->next != NULL; node = node->next);
            node->next = new Node<value_type>(it.node->data);
    }
}

// Insert at end
void push_back(value_type in)
{
    this->insert(this->end(), in);
}

unsigned size()
{
    if (this->empty()) return 0;
    unsigned i = 0;
    for (iterator it = this->begin(); it != this->end(); ++it, ++i);
    return i;
}

bool empty() const { return this->head == NULL; }
4

1 回答 1

0

在我写完这篇文章后几乎立即就解决了这个问题。

我所要做的就是首先将 head 分配给 NULL

List(List<value_type>& list)
{
    this->head = NULL;

    for (iterator it = list.begin(); it != list.end(); ++it)
        this->push_back(*it);
}
于 2013-03-11T11:14:25.440 回答