如何以先进先出的方式从数组中删除元素

本文关键字:数组 删除 元素 方式 先进先出 | 更新日期: 2023-09-27 18:33:20

C# 初学者在这里...

我有

int[] numbers = new int[10];

我想在这个数组中添加 50 个数字。数组已满后,将删除第一个添加的数字,并添加新的数字。我想在数组顶部显示最后添加的数字。如

[5,4,3,2,1...] 

 [1,2,3,4,5,...]

我怎样才能做到这一点?

提前致谢

这是我尝试过的

....
dataArray = new int[10];
....
Queue<int> numbers = new Queue<int>();
....
if (numbers.Count == 10)
        {
            numbers.Dequeue();
        }
        numbers.Enqueue(i);
        numbers.CopyTo(dataArray, numbers.Count);

我不断收到" 数组的偏移量和长度超出范围或计数大于从索引到源集合末尾的元素数"错误

如何以先进先出的方式从数组中删除元素

Array.Copy 为您尝试完成的任务提供了良好的性能。

int[] newArray = new int[10];
newArray[0] = 4;    // new value
Array.Copy(numbers, 0, newArray, 1, numbers.Length - 1);

请注意数组长度,但这是抛出异常的任何绑定问题。

我认为您应该使用队列,然后如果需要,可以将其转换为数组

class Program
    {
        static void Main(string[] args)
        {
            const int CAPACITY = 10;
            Queue<int> queue = new Queue<int>(CAPACITY);
            for (int i = 0; i < 50; i++)
            {
                if (queue.Count == CAPACITY)
                    queue.Dequeue();
                queue.Enqueue(i);
            }
            queue.ToArray();
            Console.WriteLine(queue.Count);
            Console.ReadKey();
        }
    }

看看通用的队列类,它具有您正在寻找的 FILO 结构功能。仅使用数组执行此操作...

    int[] numbers=new int[50];
    for(int i=0; i<numbers.length; i++) numbers[i]=i; 
    //fill the array with 1, 2, 3, 4...
    //To reverse this order, swap elements in reverse
    //numbers.length-1 is the last index of the array
    // j<numbers.length/2,each time you swap you change two values, so only done half the length of the array
    for(int j=numbers.length-1; j>numbers.length/2; j--) swap(numbers, j, numbers.length-j);
      //swaps the values of different indexes in the array
     void swap(int[] array, int index1, int index2) {
          int temp=array[index1];
          array[index1}=array[index2];
          array[index2}=temp;
                  }

这应该反转数组