【发布时间】:2020-09-24 00:24:52
【问题描述】:
我想制作一个快速、相对较小但输入范围较大的查找表: -输入:最大 32 位值。 (一个 32 位颜色值) -输出:最大 8 位索引。 (表的索引)
类似于下面的代码。 (如果索引的值超过 256 个,则索引将为 0)
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
static uint8_t getIndx(uint32_t value);
static uint8_t **indx;
static uint8_t count = 0;
int main(void) {
// set up the indx
const uint32_t size = 0xFFFF; // for demonstrative purposes not even nearly as large as wished to be (0xFFFFFFFF) plus my for loop below would get in trouble, I think
indx = (uint8_t**)malloc(sizeof(uint8_t*) * size);
if(indx == NULL) {
printf("could not allocate memory\n");
return 0;
}
for(int i = 0; i < size + 1; i++) {
indx[i] = NULL;
}
printf("%d\n", getIndx(111));
printf("%d\n", getIndx(222));
printf("%d\n", getIndx(333));
printf("%d\n", getIndx(111));
printf("%d\n", getIndx(222));
printf("%d\n", getIndx(333));
return 0;
}
static uint8_t getIndx(uint32_t value) {
if(indx[value] == NULL) {
if(count > 255) return 0;
indx[value] = (uint8_t*)malloc(sizeof(uint8_t));
*indx[value] = count;
count++;
}
return *(indx[value]);
}
输出是:
0
1
2
0
1
2
无论我怎么想,我总是以类似的方式结束。输入范围为 32 位(4294967296 个状态),我需要分配太多内存才能获得 256 个可能的输出。在 for 循环内形成 256 if else 也不是我想要的。
有没有什么快速的方法,不管是表还是不表,最终功能相同,我还没听说过?
提前非常感谢!
【问题讨论】:
-
听起来您可能正在寻找“哈希表”。你有没有研究过这是否符合你的需要?哈希表有多种变体,具体取决于哪种内存与性能权衡点适合您的需求。
-
谷歌搜索“c字典”带你here。
-
请注意,
if(count > 255)永远不会为真,因为count的类型为uint8_t。说表中元素的最大数量为 256 是否正确?您的目标是哪种硬件? -
你要什么?不使用太多内存的解决方案?你想要一个函数来记住它的前 256 个输入,并在它再次看到这些输入时返回它们分配的数字,而对于其他输入则返回零?
-
仅供参考,您为
size元素分配空间,但初始化size+1元素。
标签: c performance lookup-tables