2015-05-05 28 views
0

我想在C#中實現二叉搜索樹,並遵循Cormen等人的第12章來完成。要做到這一點,我需要使用可空類型,像這樣:使用可空整數訪問數組

public int insert(Node newNode) // return array index of added node 
    { 
     int? y = null; 
     int? x = this.root; 

     while (x != null) 
     { 
      y = (int)x; 
      if (newNode.key < this.tree[x]) 
      { } 

     } 

     return 0; 
    } 

現在我得到以下錯誤:

Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast)?

對於這個if (newNode.key < this.tree[x])線。
使用可爲空的類型來訪問數組索引是非法的嗎?
我可以用不同的方式初始化數組嗎?
或者我應該忘記null並且使用-1作爲例子嗎?

+0

參考['Nullable'類型](https://msdn.microsoft.com /en-us/library/1t3y8s4s.aspx),並確保它後嘗試'x.Value'我s不爲null。 – Alex

+0

如果你想真正學習數據結構和算法,我會建議在非託管環境中進行這項練習。 –

+4

@ aj.toulan:爲什麼?大多數(如果不是所有的)通用算法都可以在管理環境中很好地實現。作爲一個好處,您可以專注於實際算法,而不必擔心正確管理內存。 –

回答

0

您有x != null約束,您需要的全部是this.tree[x.Value]

目前還不清楚y是什麼,但我懷疑你需要或希望(int)演員。另外,tree[x]newNode.key是什麼類型。

Is it illegal to use nullable types to acces an array index?

Can I initialize the array maybe in a different way to allow it?

沒有

Or should I forget about null and use -1 for instance?

那要看情況。如果正確完成,兩者都可行。

+0

演員在那裏,因爲我正在嘗試一些事情來糾正錯誤。確實沒有必要,現在也不行。 –

+1

這是工作是我的意思。 –

1

Cannot implicitly convert type 'int?' to 'int'.

您試圖比較int嗎?到一個int。編譯器本質上是這樣說的:「如果int?實際上是空的,我該怎麼處理這個比較,這是編譯器無法解決的問題,所以你必須提供這個邏輯。」

換句話說,既然你已經防護,以防X是零,則使用

this.tree[x.Value] 
0

檢查變量是否HasValue如果存在使用Value

public int insert(Node newNode) // return array index of added node 
    { 
     int? y = null; 
     int? x = this.root; 

     while (x.HasValue) 
     { 
      y = x; 
      if (newNode.key < this.tree[x.Value]) 
      { 
       //your logic here 
      } 

     } 

     return 0; 
    } 
+0

'x!= null'和'x.HasValue'完全相同。 –