【问题标题】:Shifting array data structure C#移位数组数据结构C#
【发布时间】:2020-05-15 07:55:19
【问题描述】:

我很想知道是否有一种有效的方法将数据存储到具有最大数量值的容器中,当达到该值时,它开始删除最旧的值以添加新值。所有这些都以有序的方式进行(意味着新数据应该在最后一个新数据之后)。

我知道我可以使用队列来实现这一点

    q.Enqueue(1);   
    q.Enqueue(2);   
    q.Enqueue(3);  // 1 2 3

    q.Dequeue(); // 2 3 
    q.Enqueue(4); // 2 3 4   

但是为了之后遍历数据需要将队列转换为数组,我不确定它的效率如何。

也许最好有一个固定大小的数组,并有一个索引在数组已满时转移到开头,并使用一些模数魔法迭代总是向后查询从最近到最近的数据。我猜这可读性会降低,但工作效率会更高。

所以我的问题是,有没有更好的可读性和有效的方法? 此外,在使用其他数据结构(例如 List、Queue、Stack..)时,使用 ToArray() 的效率如何。什么时候应该避免这种情况?

【问题讨论】:

    标签: arrays c#-4.0 data-structures stack queue


    【解决方案1】:

    最后我决定实现我的想法。不确定这是否是最好的方法,但它可以很好地满足我的需求:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class DataHolder<T> : IEnumerable
    {
        private T[] _data;
        private int _maxSize;
        private int _currIdx;
        private int _currSize;
    
        public DataHolder(int size)
        {
            _maxSize = size;
            _data = new T[_maxSize];
            _currIdx = -1;
            _currSize = 0;
        }
    
        public void Add(T data)
        {
            if (_currSize < _maxSize) _currSize++;
    
            _currIdx = NioUtils.PositiveMod((_currIdx + 1),  _maxSize);
            _data[_currIdx] = data;
        }
    
        ///<summary>
        /// Gets the element at index. The 0 element is the last one added.
        ///</summary>
        public T GetElementAt(int index)
        {
            if (index >= _currSize)
            {
                throw new System.ArgumentException("Index out of bounds exception.", "index");
            }
    
            int shiftIndex = NioUtils.PositiveMod((_currIdx - index), _maxSize);
            return _data[shiftIndex];
        }
    
        /// Implement interface IEnumerable in order to iterate throught this object.
        public IEnumerator GetEnumerator()
        {
            int count = 0;
            int index = _currIdx;
            while (count < _currSize)
            {
                count++;
                yield return _data[index];
                index = NioUtils.PositiveMod((index - 1), _maxSize);
            }
        }
    
    }
    

    PositiveMod 在哪里:

    public static int PositiveMod(int value, int n)
    {
        int v = value % n;
        return v >= 0 ? v : n + v;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-18
      • 1970-01-01
      • 2013-04-26
      • 2022-12-22
      • 1970-01-01
      • 1970-01-01
      • 2016-06-28
      • 1970-01-01
      相关资源
      最近更新 更多