【发布时间】:2016-08-27 13:36:48
【问题描述】:
我一直在使用特定的数据结构做很多工作,我主要将其用作平面树结构中项目的索引。它由一个正整数数组(或字节、长整数或其他)组成,每个数组都被认为处于与其在数组中的索引相等的“深度”。
将其视为树中的索引,树的根有一个空数组作为其索引,索引为{a, b... c} 的给定节点的第 N 个子节点的索引为{a, b... c, N}。
对它的常见操作递增/递减数组中的最后一个数字,从前面或后面删除一些元素,并将一些元素附加到前面或后面。在树索引上下文中,这些对应于通过兄弟节点向前/向后步进,在子树中查找索引或查找父节点的索引,当树的根被卡在另一棵树上时查找索引并查找某些索引后代节点。
虽然我最初只是将它们用作索引,但我不断发现将它们用于从加速数据序列化到使代码更具可读性等目的的新方法。这让我想知道,这种数据结构或类似的东西是否在其他地方普遍使用?如果有,它有名字吗?我很想看看我还能用这个做什么。
(C# 中的示例实现,省略了错误检查以保持可读性)
class TreeIndex
{
public readonly int depth
{
get
{
return widths.Length;
}
}
public readonly int[] widths;
public TreeIndex()
{
widths = new int[0];
}
public TreeIndex(params int[] indices)
{
widths = indices;
}
public static implicit operator int(TagIndex ti)
{
return ti[ti.depth - 1];
}
public static operator TagIndex +(TagIndex ti, int i)
{
int[] newwidths = ti.widths.Clone();
newwidths[newwidths.Length - 1] += i;
return new TagIndex(newwidths);
}
public static operator TagIndex -(TagIndex ti, int i) { return ti + (-i); }
public static operator TagIndex <<(TagIndex ti, int i)
{
int[] newwidths = new int[ti.depth - i];
Array.Copy(ti.widths, newwidths, ti.depth - i);
return new TagIndex(newwidths);
}
public static operator TagIndex >>(TagIndex ti, int i)
{
int newwidths = new int[ti.depth - i];
Array.Copy(ti.widths, i, newwidths, 0, ti.depth - i);
return new TagIndex(newwidths);
}
public static operator TagIndex ^(TagIndex tia, TagIndex tib)
{
int newwidths = new int[tia.depth + tib.depth];
Array.Copy(tia.widths, newwidths, tia.depth);
Array.Copy(tib.widths, 0, newwidths, tia.depth, tib.depth);
return new TagIndex(newwidths);
}
}
【问题讨论】:
-
尽管有重载的运算符和具体的用例,但作为一个数据结构,这实际上只是一个列表。
-
是这样吗?我不太清楚什么构成了我认为的独特数据结构。我见过许多类似的问题,似乎是根据操作而非内容来定义它们,这是不正确的吗?
标签: arrays data-structures terminology