我不知道为什么这段代码不起作用......
#include <iostream>
using namespace std;
struct Triple {int row, col, value;};
class Matrix;
class MatrixNode
{
friend class Matrix;
friend istream& operator>>(istream&, Matrix&);
private:
MatrixNode *down, *right;
bool head;
union {
MatrixNode *next;
Triple triple;
};
MatrixNode(bool, Triple*);
};
MatrixNode::MatrixNode(bool b, Triple* t)
{
head = b;
if (b) {right = down = this;}
else triple = *t;
}
class Matrix {
friend istream& operator>>(istream&, Matrix&);
public:
~Matrix();
private:
MatrixNode *headnode;
};
istream& operator>>(istream& is, Matrix& matrix)
{
Triple s;
cout << "Enter the numbers of row, colume, value" << endl;
is >> s.row >> s.col >> s.value;
int p = max(s.row, s.col);
matrix.headnode = new MatrixNode(false, &s);
if (p == 0) { matrix.headnode->right = matrix.headnode; return is;}
MatrixNode **head = new MatrixNode*[p];
for (int i = 0; i < p; i++)
head[i] = new MatrixNode(true, 0);
int currentRow=0;
MatrixNode *last = head[0];
for (int i = 0; i < s.value; i++)
{
Triple t;
cout << "Enter the terms" << endl;
is >> t.row >> t.col >> t.value;
if (t.row > currentRow){
last -> right = head[currentRow];
currentRow = t.row;
last = head[currentRow];
}
last = last -> right = new MatrixNode(false, &t);
head[t.col]->next = head[t.col]->next->down = last;
}
last -> right = head[currentRow];
for (int i = 0; i < s.col; i++)
head[i] -> next -> down = head[i];
for(int i = 0; i < p - 1; i++)
head[i] -> next = head[i+1];
head[p-1] -> next = matrix.headnode;
matrix.headnode -> right = head[0];
delete [] head;
return is;
}
int main()
{
Matrix *a = new Matrix;
Matrix *b = new Matrix;
cin >> *a;
cin >> *b;
}
答案 0 :(得分:1)
具体问题是head[t.col]->next
未初始化,而您正在取消引用它。
更普遍的问题是你咬的比你嚼得多。你正试图建立一个远远超出你能力的东西,而你正试图一步到位。尝试构建一个更简单的链表,例如,没有联合的链表,没有运算符&gt;&gt;和只有一个维度,而不是三个。一旦您对此感到满意,就可以通过小步骤逐步完成更高级的结构。