2014-01-18 47 views
0

我有問題:重新使用結構的陣列型結構的陣列處理

1D陣列(反式)是全球性的:

struct Transaction 
{ 
    int Item; 
    float prob; 
    int support; 
    Transaction *next; 
}; 

#define ItemNum 1000 
Transaction *Trans[ItemNum]; 
Transaction *PairItems[ItemNum][ItemNum]; 

我初始化反式爲:

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++; 
     } 

到現在爲止,一切都還好,

當我再次嘗試使用 ,我不能,因爲陣列變空了!

例如,如果我這樣做的代碼:

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++; 
     } 

編譯器將忽略此條件:

而(!反式[K] = NULL)

因爲Trans [k] = NULL。我不知道方式!

但是,當我刪除打印代碼時,Trans [k]!= NULL並且編譯器進入條件並執行其餘的操作!!

我覺得跟初始化結構的陣列相關的問題,但我無法找到解決辦法

請幫助

感謝

+0

您的''++'在while循環之外!(第二位代碼) –

+0

** i **指代文本文件中的當前行/行。我想填充結構** Trans **的數組,使得:** Trans [0] = **文件中的項目集合(將文件第一行中的所有元素提取並存儲爲鏈接列表),以及** Trans [1] = **來自文件的一組項目(將文件的第二行中的所有元素提取並存儲爲鏈接列表),依此類推。 – NHA

+0

有點相關:確認這些數組並不在'main()'中,尤其是第二個,在32位實現中*最小*僅爲4MB。如果本地的'main()'和這個*工程*,你的堆棧比我當然要強大得多。此外,填充鏈接表格的方式也相當簡單。 – WhozCraig

回答

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而不是手寫列表的硬編碼數組。

+0

非常感謝你,我沒有注意到我重新在我的陣列中注意!我不是新編程方式(使用向量和列表)的專家,但是介紹他們的坦克。我相信我必須學習他們,因爲我會處理大文件。 – NHA