将“N”个记录存储在固定大小的数组中(store “N” number of records within an array of a fixed size)

编程入门 行业动态 更新时间:2024-10-11 23:16:29
将“N”个记录存储在固定大小的数组中(store “N” number of records within an array of a fixed size)

是否可以在数组内存储一组滚动值而不超出设定的索引?

例如,我将一个基本的控制台例子放在一起,如下所示:

static void Main(string[] args) { int[] myvalue; myvalue = new int[10]; for (int i = 0; i < 20; i++) { Console.WriteLine("Array {0} is {1}", i, myvalue[i]); } Console.ReadLine(); }

在目前的方法中,我得到一个索引越界异常。 我想要做的是将数组限制为10个项目,但随着计数增加用新值覆盖现有项目。 因此,我可以迭代100次,但数组只会显示程序结尾的最后十个值(89-99)。

如果数组不是最好的方法,我会欢迎任何有关如何将其存储在内存中的建议。

谢谢

Is it possible to store within an array a rolling set of values without exceeding the set index?

For example I put together a basic console example at as follows:

static void Main(string[] args) { int[] myvalue; myvalue = new int[10]; for (int i = 0; i < 20; i++) { Console.WriteLine("Array {0} is {1}", i, myvalue[i]); } Console.ReadLine(); }

In the current approach I get an index out of bounds exception. What I would like to do is to limit the array to 10 items but as the count increases overwrite the existing items with new values. Therefore I could iterate through 100 times but the array would only show the last ten values (89-99) at the end of the routine.

If an array is not the best approach I would welcome any suggestions as to how to store this in memory.

thank you

最满意答案

您可以使用List来存储这些值,然后包装Add方法来处理项目数量的限制。 这将为您处理所有“滑下”逻辑。

const int MAX_ITEMS = 10; List<int> list = new List<int>(); void AddItem(int k) { list.Add(k); if (list.Count > MAX_ITEMS) { // discard the item at the front of the list list.RemoveAt(0); } }

无论何时您想添加一个值,只需调用AddItem(n) ,例如:

for (int i = 0; i < 100; i++) { AddItem(i); }

无论何时你想读出数值,你都可以简单地做到:

for (int i = 0; i < list.Count; i++) { Console.WriteLine(list[i]); }

这也有一个好处,就是你可以放置少于最大数量的项目(比如你只有6个而不是10个),它仍然可以正常工作(你不必担心未填充的数组项)。

You could use a List to store the values, then wrap the Add method to handle the limit on the number of items. This would take care of all the "slide down" logic for you.

const int MAX_ITEMS = 10; List<int> list = new List<int>(); void AddItem(int k) { list.Add(k); if (list.Count > MAX_ITEMS) { // discard the item at the front of the list list.RemoveAt(0); } }

Whenever you want to add a value, you just call AddItem(n), for example:

for (int i = 0; i < 100; i++) { AddItem(i); }

Whenever you want to read out the values, you can simply do:

for (int i = 0; i < list.Count; i++) { Console.WriteLine(list[i]); }

This also has the advantage that you can put less than the maximum number of items in (say you only have 6 instead of 10) and it will still work correctly (you don't have to worry about unfilled array items).

更多推荐

本文发布于:2023-04-29 02:51:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1334456.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   大小   store   number   size

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!