每个节点4个字符的字符串双向链表

问题描述

我想接受一长串数字并插入到一个双向链表中,每个节点有 4 个字符(数字)。 下面是我的代码。它将输入作为数字,但说“程序已完成,存在代码 0” 请帮助我在这里错过了什么?


#include <iostream>
#include <string>
#include <conio.h>

using namespace std;
struct Node {
  string data;
  struct Node* prev;
  struct Node* next;
};
struct Node* head = NULL;
void insert(string newdata) {
  struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));
  newnode->data = newdata;
  newnode->prev = NULL;
  newnode->next = head;
  if (head != NULL)
    head->prev = newnode;
  head = newnode;
  cout << "\nNode inserted";
}

void display() {
  struct Node* ptr;
  ptr = head;
  while (ptr != NULL) {
    cout << ptr->data << " ";
    ptr = ptr->next;
  }
}
int main() {
  string n1,temp;
  cout << "Enter the number\n";
  cin >> n1;
  int len,i;
  len = n1.size();
  cout << "\n Length is " << len;
  getch();
  // temp= n1;

  // cout<<"\n line is "<<temp.substr(len);

  for (i = 0; i < len; i = i + 4) {
    //     temp = n1.substr(i,4);
    insert(n1.substr(i,4));
  }

  cout << "\nThe doubly linked list is: ";
  display();
  return 0;
}

解决方法

正如评论部分已经指出的那样,问题在于未调用 std::string 对象的构造函数,因此该对象未正确初始化。

对此最直接的解决方法是使用 placement new,它实际上除了调用构造函数之外什么都不做。为此,您可以更改行

newnode->data = newdata;

new (&newnode->data) string( newdata );

这将调用 std::string 对象上的复制(或移动)构造函数。

然而,对这个问题的更 C++ 风格的解决方案是根本不使用 malloc,而是使用 new,并为 struct Node 编写一个适当的构造函数,它调用 string 对象的复制或移动构造函数。为此,您可以像这样定义 struct Node

struct Node {

    //copy and move constructor
    Node( const string  &data,Node* prev = nullptr,Node* next = nullptr )
        : data(data),prev(prev),next(next) {}
    Node( const string &&data,next(next) {}

    string data;
    struct Node* prev;
    struct Node* next;
};

现在您可以替换线条

struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));
newnode->data = newdata;
newnode->prev = NULL;
newnode->next = head;

用这一行:

Node* newnode = new Node( newdata,nullptr,head );