[英]Singly linked list C++ ostream and istream — outputs memory addresses
我对此确实很陌生,现在正在学习单链表。 我正在写一些代码,但我真的很困惑。 我正在尝试编写一个读取方法和一个写入方法。 我有一个无法更改的测试装置。 我只希望能够读取流并输出流,这样它就不会随内存地址一起返回。
谁能以一种非常简单的方式进行解释,并帮助我修复此代码?
void SLLIntStorage::Read(istream& r)
{
char c[13];
r >> c;
r >> NumberOfInts;
Node *node = new Node;
head = node; //start of linked list
for(int i = 0; i < NumberOfInts; i++) //this reads from the file and works
{
r >> node->data;
cout << node->data << endl;
node ->next = new Node; //creates a new node
node = node->next;
}
}
void SLLIntStorage::Write(ostream& w)
{
Node *node = new Node;
head = node;
for(int i = 0; i < NumberOfInts; i++)
{
w << node->data << endl;
//cout << i << endl;
}
}
并在头文件中
#pragma once
#include <iostream>
using namespace std;
struct Node
{
int data; //data in current node
Node *next; //link of address to next node
};
class SLLIntStorage
{
private:
Node *head;// start of linked list
//Node *tail;
Node current; //current node
public:
void setReadSort(bool);
void sortOwn();
void Read(istream&);
void Write(ostream&);
void add(int i);
void del();
bool _setRead;
int NumberOfInts;
SLLIntStorage(void);
~SLLIntStorage(void);
};
inline ostream& operator<< (ostream& out, SLLIntStorage& n)
{
n.Write(out);
return out;
}
inline istream& operator>> (istream& in, SLLIntStorage& s)
{
s.Read(in);
return in;
}
谢谢!
您的写入方法似乎有些混乱。 您要编写元素,而不是创建新元素。 这样的事情应该更好地工作:
void SLLIntStorage::Write(ostream& w)
{
Node *node = head;
for(int i = 0; i < NumberOfInts; i++)
{
w << node->data << endl;
node = node->next;
//cout << i << endl;
}
}
顺便说一句:您的实现似乎对我有用的方式,您可能会发生很大的内存泄漏。 一旦Read方法连续两次被调用,旧列表将被丢弃而不释放内存。 您应该考虑在保存另一个文件的同时调用write时您的类应该做什么。 追加吗? 首先删除旧列表?
在Write()方法中,通过执行以下操作来破坏整个列表
Node *node = new Node;
head = node;
如果您问我,这将整个列表替换为一个空列表。 NumberOfInts不再正确,您将继续打印相同的节点->数据NumberOfInts次。
我不知道从哪里开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.