簡體   English   中英

實現索引隊列的有效方法(在O(1)時間內可以通過索引檢索元素)?

[英]Efficient way to implement an indexed queue (where elements can be retrieved by index in O(1) time)?

根據.NET隊列ElementAt性能 ,使用ElementAt按索引訪問項目顯然不是一個合理的選擇。

是否有適合此要求的替代通用數據結構?

我的隊列有固定的容量。

根據Queue類上的MSDN條目 ,“ 此類將隊列實現為循環數組 ”,但它似乎沒有公開任何類型的索引屬性。

更新 :我找到了C5的CircularQueue實現 這似乎符合要求,但如果可能,我寧願不必導入另一個外部庫。

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]; 
        }
    }        
}

您可以使用循環數組 即在數組中實現隊列。

實現非常簡單,您不需要使用外部庫,只需自己實現。 提示:使用m_beginIndex, m_nElements成員比m_beginIndex, m_endIndex更容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM