【问题标题】:Efficient way to implement an indexed queue (where elements can be retrieved by index in O(1) time)?实现索引队列的有效方法(可以在 O(1) 时间内通过索引检索元素)?
【发布时间】:2011-10-12 14:03:51
【问题描述】:

根据.NET queue ElementAt performance,使用 ElementAt 按索引访问项目显然不是一个合理的选择。

是否有适合此要求的替代通用数据结构?

我的队列有固定容量。

根据MSDN entry on the Queue class,“此类将队列实现为循环数组”,但它似乎没有公开任何类型的索引属性。

更新:我找到了C5's implementation of a CircularQueue。它似乎符合要求,但如果可能的话,我宁愿不必导入另一个外部库。

【问题讨论】:

    标签: c# .net performance indexing queue


    【解决方案1】:

    您可以使用cyclic array。 IE。在数组中实现队列。

    实现很简单,不需要使用外部库,自己实现即可。提示:使用m_beginIndex, m_nElements 成员比使用m_beginIndex, m_endIndex 更容易。

    【讨论】:

      【解决方案2】:
      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]; 
              }
          }        
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-18
        • 1970-01-01
        • 2015-08-15
        • 2012-10-24
        • 1970-01-01
        • 2013-12-03
        • 2012-04-09
        相关资源
        最近更新 更多