我遇到问题:重新使用struct
数组1D阵列(Trans)是全局的:
struct Transaction
{
int Item;
float prob;
int support;
Transaction *next;
};
#define ItemNum 1000
Transaction *Trans[ItemNum];
Transaction *PairItems[ItemNum][ItemNum];
我将Trans初始化为:
for (int a = 0; a <= ItemNum - 1; a++)
Trans[a] = NULL;
然后我用文本文件的输入填充这个数组。具体来说:
i = 0;
while (!inFile.eof())
{
FollowingItem = NULL;
getline(inFile, line);
std::stringstream in(line);
while (in >> a >> b)
{
NewItem = new Transaction;
NewItem->Item= a;
NewItem->prob = b;
NewItem->next = NULL;
if (Trans[i] == NULL)
Trans[i] = FollowingItem = NewItem;
else
{
FollowingItem->next = NewItem;
FollowingItem = NewItem;
}
}
i++;
}
然后,我打印出来:
i=0;
while (Trans[i] != NULL)
{
while (Trans[i] != NULL)
{
cout << Trans[i]->Item << " " << Trans[i]->prob<<" ";
Trans[i] = Trans[i]->next;
}
cout << "\n";
i++;
}
直到现在,一切都还好,
BUT
当我再次尝试使用 Trans 时,我不能,因为数组变空了!
例如,如果我执行此代码:
for (int a = 0; a <= ItemNum - 1; a++)
for (int b = 0; b <= ItemNum - 1; b++)
{
PairItems[a][b] = new Transaction;
PairItems[a][b]->support = 0;
}
int k = 0;
while (Trans[k] != NULL)
{
int l = 0;
while (Trans[l] != NULL)
{
PairItems[k][l]->Item = Trans[k]->Item;
PairItems[k][l]->prob = Trans[k]->prob;
PairItems[k][l]->support += 1;
cout << PairItems[k][l]->Item << " " ;
Trans[k] = Trans[k]->next;
l++;
}
cout << "\n";
k++;
}
编译器忽略了这个条件:
while(Trans [k]!= NULL)
因为 Trans [k] = NULL 。我不知道!
但是当我删除打印代码时, Trans [k]!= NULL ,编译器进入条件并执行其余的操作!!
我认为与初始化结构数组有关的问题,但我找不到解决方案
请帮助
由于
答案 0 :(得分:1)
您的打印代码会修改数组,尤其是Trans[i] = Trans[i]->next;
您的打印功能可能写得:
for (int i = 0; Trans[i] != NULL; ++i) {
for (const Transaction* it = Trans[i]; it != NULL; it = it->next) {
std::cout << it->Item << " " << it->prob <<" ";
}
cout << "\n";
}
顺便说一句,您可以使用std::vector<std::list<Transaction> > Trans
而不是硬编码的手写列表数组。