使用可为空的整数访问数组

Using nullable integer to access array

我正在尝试在 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 例如?

您已经设置了 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?

这取决于。如果正确完成,两者都是可行的。

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

您正在尝试比较一个整数?到一个整数。编译器本质上是在说“如果 int? 实际上是 null,我应该如何处理这个比较。这是一个编译器无法解决的问题,因此您必须提供该逻辑。

换句话说,既然你已经防止 x 为 null,那么使用

this.tree[x.Value]

检查变量是否存在 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;
    }