所以我试图完全从头开始制作一个程序(不包括任何库)并且我有一个非常难看的函数:
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;
}
它的丑陋部分源于我需要一种方法将 char
acters 关联到 int
egers ('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/