稀疏阵用C!如何做到呢?我可以ALLOC一个数组只有部分? [英] Sparse Array in C! How accomplish it? Can I alloc only parts of an array?

查看:106
本文介绍了稀疏阵用C!如何做到呢?我可以ALLOC一个数组只有部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一个问题是:我如何在C简单的稀疏阵列(一维只)? {用我自己的手,没有图书馆。}

The first question is: "How I do a simple sparse array in C (with one dimension only)?" {with my own hands, without libraries.}

和最后一个:我可以分配一个数组只有部分

And the last one: "Can I allocate only parts of an array?"

像*阵列;

然后使用malloc分配一些纪念品本;
所以,我们说自由,我们不希望指数。

then use malloc to allocate some mem for this; so, We free the index that we don't want.

我能做到吗?

太感谢了!

推荐答案

没有,你不能做到这一点。

No, you can't do it.

你可以做的是分配块,但你需要仔细设计它。

What you can do is to allocate blocks, but you need to design it carefully.

也许是最好的优化是使用电池的范围。所以,你可以使用可用范围的链表(或地图):

Probably the best optimization is to use ranges of cell. So you can use a linked list (or a map) of available ranges:

struct SparseBlock
{
  void *blockData;
  int beginIndex;
  int endIndex;
  struct SparseBlock *next;
}

显然,如果 endIndex的 - beginIndex = 0 你有一个单元格(即数组里面分离出来),否则,你已经得到的细胞块,让您分配内存为它各适量。

obviously if endIndex - beginIndex = 0 you have a single cell (that is isolated inside the array), otherwise you have got a block of cells, allowing you to allocate the right amount of memory for it.

这方法很简单不可变稀疏向量,否则你应该照顾

This approach is simple for immutable sparse vectors, otherwise you should take care of


  • 重组每当孔填充或生成的块

  • 只存储单个细胞

另外,你必须决定指数如何将这些块,你可以让他们在一个链表排序,也可以使用一个地图有一个恒定的O(1)时间检索第n个块(当然你将不得不插入许多相同的键对同一个块,如果它是一个范围或降低指数提供的最接近的较低索引)。

In addition you have to decide how to index these blocks, you can keep them ordered in a linked list, or you can use a map to have a constant O(1) time to retrieve a n-th block (of course you will have to insert many equal keys for the same block if it's a range or reduce the index to the nearest lower index available).

解决方案有很多,只是前preSS你的创造力! :)

Solutions are many, just express your creativity! :)

这篇关于稀疏阵用C!如何做到呢?我可以ALLOC一个数组只有部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆