c - 在纯 C 中,如何制作相当于 "map"的内容?

标签 c dictionary data-structures

所以我试图完全从头开始制作一个程序(不包括任何库)并且我有一个非常难看的函数:

int parseUnsignedInt ( char * ch, unsigned int * ui )
{
/* Starting at character ch, reads the unsigned int into the
       variable ui, returns the number of characters read.
*/
    ui = 0; // unsigned integer into which the string representation is read 
    int m = 1; // multiplier
    int ncp = 0; // # of characters parsed
    while (*ch)
    {
        bool chid = false; // ch is a decimal
        for (int k = 0; k < decmapLength; ++k)
        {
            if (decmap[k].cval == *ch)
            {
                ui += decmap[k].ival * m;
                m *= 10;
                chid = true;
                break;
            }
        }
        if (!chid) break;
        ++ncp;
        ++ch;
    }
    return ncp;
}

它的丑陋部分源于我需要一种方法将 characters 关联到 integers ('0'->0, '1'-> 1, ..., '9'->9) 并制作了一个数组或结构

typedef struct icpair
{
    char cval;
    int ival;
} icpair;

icpair decmap [10] = {{'0',0}, {'1',1}, {'2',2}, {'3',3}, {'4',4}, {'5',5}, {'6',6}, {'7',7}, {'8',8}, {'9',9}};
int decmapLength = sizeof(decmap)/sizeof(icpair);

为此目的。但是,查找一个值,如果它甚至存在,如果在纯 C 中有更好的方法来执行此操作,则可以压缩的难看的行数。我也希望它是可靠的,所以没有像这样的 ASCII 值减法'9'-'ch'。这在纯 C 中是否可行?如果可行,它是如何实现的?

最佳答案

用 C 编写的简单 map API 可能如下所示:

Map * map_create(void);
void map_insert(Map * map, char key, int value);
int map_find(Map * map, char key);
void map_destroy(Map * map);

然后您就可以执行 map_find(map, '0') 来获取整数值,如果不是,则可能具有返回 -1 的语义找不到。

根据您的需要,可以使用多种不同的数据结构来实现这一点。如果您不关心维护顺序,哈希表可能是最合适的。如果您确实需要维护基于键的顺序,例如,二叉树可能是更好的主意(也许是红黑树)。

您可以修改 API 以将 void * 作为键和值以对其进行一些概括(在没有泛型的情况下,C 缺少泛型)。会增加复杂性,例如为哈希表提供哈希函数或为二叉树提供比较函数。

也就是说,执行 *ch - '0' 是安全的,并且工作正常。

关于c - 在纯 C 中,如何制作相当于 "map"的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29885973/

相关文章:

c - 警告 : assignment makes pointer from integer without a cast [-Wint-conversion]

python - 在函数中使用用户输入以及带有用户输入的字典

python - 更改 python dict 中的键并仅打印带有值的键值

c - 在 BST 中找到添加到 k 的节点对

c - C 结构中的松弛字节

c - 尝试将指针索引到函数中的指针时出现段错误

data-structures - 如何使用 HashSet 实现 HashTable

c++ - 迭代器实现——(链表队列)

c++ - 如何查看用 C/C++ 编写的函数的源代码?

c++ - 在 map/unordered_map 中使用多个键(多维)