Cra*_*mer 6 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;
}
Run Code Online (Sandbox Code Playgroud)
其丑陋的一部分的事实,我需要一种方法来关联茎characters到int和由阵列或结构egers( - > 1,...,"9" - > 9"0" - > 0,"1")
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);
Run Code Online (Sandbox Code Playgroud)
为了这个目的.但是,查找一个值,如果它存在,则说明如果有更好的方法在纯C中执行此操作,可以压缩的难看的行数.我也希望这是可靠的,所以没有ASCII值减法'9'-'ch'.这在纯C中是否可行,如果是这样,它是如何实现的?
C 语言的简单地图 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);
Run Code Online (Sandbox Code Playgroud)
然后您就可以map_find(map, '0')获取整数值,也许可以使用-1如果未找到则返回的语义。
根据您的需要,可以使用许多不同的数据结构来实现这一点。如果您不关心维护顺序,那么哈希表可能是最合适的。例如,如果您确实需要维护基于键的顺序,那么二叉树可能是一个更好的主意(可能是红黑树)。
您可以修改 API 以获取void *键和值,以对其进行一些概括(在没有泛型的情况下,而 C 缺乏泛型)。会增加复杂性,例如为哈希表提供哈希函数或为二叉树提供比较函数。
也就是说,这样做*ch - '0'是安全的,而且效果会很好。