C# 实现索引队列的有效方法(其中可以在O(1)时间内通过索引检索元素)?
根据,使用ElementAt通过索引访问项目显然不是一个合理的选择 是否有适合此要求的替代通用数据结构 我的队列有固定的容量 正如所说,“此类将队列实现为循环数组”,但它似乎没有公开任何类型的索引属性 更新:我找到了。它似乎符合要求,但如果可能的话,我宁愿不必导入另一个外部库。您可以使用。即在数组中实现队列 实现非常简单,您不需要使用外部库,只需自己实现即可。提示:使用C# 实现索引队列的有效方法(其中可以在O(1)时间内通过索引检索元素)?,c#,.net,performance,indexing,queue,C#,.net,Performance,Indexing,Queue,根据,使用ElementAt通过索引访问项目显然不是一个合理的选择 是否有适合此要求的替代通用数据结构 我的队列有固定的容量 正如所说,“此类将队列实现为循环数组”,但它似乎没有公开任何类型的索引属性 更新:我找到了。它似乎符合要求,但如果可能的话,我宁愿不必导入另一个外部库。您可以使用。即在数组中实现队列 实现非常简单,您不需要使用外部库,只需自己实现即可。提示:使用m\u beginIndex,m\u nements成员比使用m\u beginIndex,m\u endIndex公共类索引队
m\u beginIndex,m\u nements
成员比使用m\u beginIndex,m\u endIndex
公共类索引队列更容易
public class IndexedQueue<T>
{
T[] array;
int start;
int len;
public IndexedQueue(int initialBufferSize)
{
array = new T[initialBufferSize];
start = 0;
len = 0;
}
public void Enqueue(T t)
{
if (len == array.Length)
{
//increase the size of the cicularBuffer, and copy everything
T[] bigger = new T[array.Length * 2];
for (int i = 0; i < len; i++)
{
bigger[i] = array[(start + i) % len];
}
start = 0;
array = bigger;
}
array[(start + len) % array.Length] = t;
++len;
}
public T Dequeue()
{
var result = array[start];
start = (start + 1) % array.Length;
--len;
return result;
}
public int Count { get { return len; } }
public T this[int index]
{
get
{
return array[(start + index) % array.Length];
}
}
}
{
T[]阵列;
int启动;
内伦;
公共IndexedQueue(int initialBufferSize)
{
数组=新的T[initialBufferSize];
开始=0;
len=0;
}
公共无效排队(T)
{
if(len==array.Length)
{
//增加cicularBuffer的大小,并复制所有内容
T[]更大=新的T[array.Length*2];
对于(int i=0;i