【问题标题】:String Doubly Linked List of 4 characters each node每个节点 4 个字符的字符串双向链表
【发布时间】:2021-05-30 20:15:22
【问题描述】:

我想接受一长串数字并插入到双向链表中,每个节点有 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;
}

【问题讨论】:

  • 您不能将mallocNode 一起使用,因为Node 的构造函数不会运行并且您将访问一个未初始化的字符串对象。使用newnode = new Node;(并为 Node 提供一个适当的构造函数,这样您就不必分配给每个字段)。
  • 另一种方法是使用placement new 就地显式构造string 对象。但是,这不是好的 C++ 编程风格。但它会更符合 OP 的 C 风格的解决方案。

标签: c++ string doubly-linked-list


【解决方案1】:

正如在 cmets 部分中已经指出的,问题在于 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, Node* prev = nullptr, Node* next = nullptr )
        : data(data), prev(prev), 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 );

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-24
相关资源
最近更新 更多