C 字典/地图
我想映射结构成员,这样我就可以消除循环中的 if 分支。在 C 中实现此功能的最佳方法或约定是什么?我想它可能是一个二维数组......然后我可以将整数映射到 char 键?
char chunk[32];
int n;
int i;
char *ptr = config;
while (*ptr != '\0') {
int items_read = sscanf(ptr, "%31[^;]%n", chunk, &n);
if(chunk[0] == 'S' && chunk[1] == 'P') {
for(i=0;i<GLOBAL_MEAS_CUTOFF; i++) {
theMeas[i].signal_path = atoi(&chunk[2]);
}
}
if(chunk[0] == 'T' && chunk[1] == 'L') {
for(i=0;i<GLOBAL_MEAS_CUTOFF; i++) {
theMeas[i].trace_length = atoi(&chunk[2]);
}
}
if(chunk[0] == 'S' && chunk[1] == 'R') {
for(i=0;i<GLOBAL_MEAS_CUTOFF; i++) {
theMeas[i].sample_rate = atoi(&chunk[2]);
}
}
chunk[0]='\0';
if (items_read == 1)
ptr += n;
if ( *ptr != ';' ) {
break;
}
++ptr;
}
I want to map struct members so I can eliminate if branches in a loop. What is the best way or convention to implement this in C? I suppose it could be a 2 dimensional array instead...then I could map integers to the char keys?
char chunk[32];
int n;
int i;
char *ptr = config;
while (*ptr != '\0') {
int items_read = sscanf(ptr, "%31[^;]%n", chunk, &n);
if(chunk[0] == 'S' && chunk[1] == 'P') {
for(i=0;i<GLOBAL_MEAS_CUTOFF; i++) {
theMeas[i].signal_path = atoi(&chunk[2]);
}
}
if(chunk[0] == 'T' && chunk[1] == 'L') {
for(i=0;i<GLOBAL_MEAS_CUTOFF; i++) {
theMeas[i].trace_length = atoi(&chunk[2]);
}
}
if(chunk[0] == 'S' && chunk[1] == 'R') {
for(i=0;i<GLOBAL_MEAS_CUTOFF; i++) {
theMeas[i].sample_rate = atoi(&chunk[2]);
}
}
chunk[0]='\0';
if (items_read == 1)
ptr += n;
if ( *ptr != ';' ) {
break;
}
++ptr;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我怀疑你(理想情况下)想要的是一本字典:
当然,上述语法在 C 中永远不会发生,但这在这里并不重要。问题是您必须编写实现字典数据类型的所有代码,我怀疑这有点过分了。
所以我怀疑你(真正)想要的是一种可以在循环中使用名称的方法:
我在这里告诉你你可以做到这一点!最简单的方法是使用
enum
:使用数组代替
struct
成员:要索引“成员”,请使用:
您可以循环遍历所有“成员” ,”你可以使用这个:
当你想要进行基于字符的比较时,这确实会有点崩溃,但我们可以做一点:
你的
if
语句可以替换为:或者,更安全:
这是我所能得到的最接近的了。
请注意,我特意使用了命名方案来促进宏的创建,这些宏将自动完成大部分工作。让我们试试:
用法:
最后一点看起来还不错。它仍然允许您通过
theMeas[i][signal_path]
进行类似于struct
的访问,但允许您迭代“成员”,并隐藏大部分宏背后的繁重工作。to_str
和from_str
函数需要更多的宏技巧才能实现自动化。您可能需要研究一下 P99。对于一般情况,我不推荐使用from_abv
函数,因为我们无法保证下次创建可迭代字段时将使用带下划线的名称。 (当然,您可以删除from_abv
函数并为您的成员提供难以理解的名称,例如SP
、TL
和SR
,允许您直接将它们与字符串数据进行比较,但您需要将strcmp
更改为memcmp
,其大小参数为(sizeof( #x) - 1)
。然后,您拥有from_abv
的所有位置都只需使用from_str
,它会自动为您生成。)但是,
from_abv
并不难定义,老实说,您可以直接将上面的if
块复制并粘贴到其中 - 它会稍微更有效,但如果您添加一个“成员”,你必须更新该函数(如所写,如果你添加一个成员,它会自行更新。)I suspect what you (ideally) want is a dictionary:
Of course, the above syntax will never happen in C, but that's not really important here. The problem is that you would have to write all the code implementing a dictionary data type, and I suspect that's overkill.
So I suspect what you (really) want is a way to have names that can be used in a loop:
And I'm here to tell you that you can do this (kind of)! The simplest way is with an
enum
:Instead of
struct
members, you use an array:To index a "member", use this:
You can loop through all the "members," you can use this:
This does break down a little when you want to get character-based comparisons, but we can do a little bit:
Your
if
statements could be replaced with:Or, more safely:
Which is about as close as I can get.
Note that I've deliberately used a naming scheme to facilitate the creation of macros that will automate much of this. Let's try:
Usage:
That last bit doesn't seem so bad. It still allows you something close to
struct
-like access viatheMeas[i][signal_path]
, but allows you to iterate over the "members," and hides most of the heavy lifting behind macros.The
to_str
andfrom_str
functions take a little more macro trickery to automate. You'll probably need to look into P99 for that. Thefrom_abv
function isn't something I'd recommend for the general case, as we have no way of guaranteeing that the next time you make iterable fields you'll use names with underscores. (Of course, you could drop thefrom_abv
function and give your members inscrutable names likeSP
,TL
, andSR
, allowing you to directly compare them to your string data, but you'd need to change thestrcmp
to amemcmp
with a size argument of(sizeof(#x) - 1)
. Then all the places you havefrom_abv
you'd just usefrom_str
, which can be automatically generated for you.)However,
from_abv
isn't hard to define, and you could honestly just copy and paste yourif
blocks from above into it - it'd be slightly more efficient, though if you added a "member" you'd have to update the function (as written, it'll update itself if you add a member.)C 支持指向函数的指针,因此您可以创建一个数组指向函数的指针并根据您的输入对数组进行寻址。这将要求您使用相同的签名实现其他功能。
另一种方法可能是将 if 子句封装在单独的函数中并使用参数调用它。
然而,我认为无论哪种方式,你都不会获得太多的加速(如果有的话)。
C supports pointers to functions, so you could create an array of pointers to functions and address the array according to your input. This would require you to implement additional functions with same signatures.
Another way might be to encapsulate the if-clauses in a separate function and calling it with the arguments.
However, I think neither way you will gain much speedup, if any.
您可以使用指向整数的指针重写您的逻辑,如下所示:
这种方法将有关要更改哪个变量(
if
语句)的决定与实际执行常见工作的代码分开。每种情况(for
循环)。您当然需要检查
p == NULL
是否为chunk[0]
和chunk[1]
与您的任何内容不匹配正在期待。You might rewrite your logic something like this, using a pointer to an integer:
This approach separates the decision about what variable to change (the
if
statements) from the code that actually does the work that is common to each case (thefor
loop).You will of course want to check whether
p == NULL
in casechunk[0]
andchunk[1]
didn't match anything you were expecting.不幸的是,对于简单的 C99,这是不可能的,因为数组索引只能是无符号整数。但可能
strncmp()
函数更适合您?Unfortunately with simple C99 this is not possible, since array indices can only be unsigned integers. But propably the
strncmp()
function suits you more?如果(这是一个相当大的如果)您可以依赖数据始终是这三个选项之一,那么我们可以在这三种情况下构造一个“最小完美哈希”。假设字符集是 ASCII(或与 ASCII 一致):
因此,S+P 是 3 mod 4,T+L 是 0 mod 4,S+R 是 1 mod 4。不是最小的,但足够接近:
您可能更喜欢使用宏或内联函数给这只猪涂上口红,或者用
char *fieldptr
代替int *fieldptr
,从((char*)theMeas 开始) + offset
,并每次将其增加sizeof(Mea)
。如果您不能依赖友好的数据,那么您至少需要某种类型的分支(条件或通过函数指针的调用),以避免在数据错误的情况下编写任何内容。即使将其保持为 1,您也可能需要 3 个案例的 64k 条目查找表,这有点稀疏,因此您可能最好使用条件语句。
If (and it's a fairly big if) you can rely on the data always being one of those three options, then we could construct a "minimal perfect hash" over the three cases. Assuming the charset is ASCII (or consistent with ASCII):
So, S+P is 3 mod 4, T+L is 0 mod 4, and S+R is 1 mod 4. Not minimal, but close enough:
You might prefer to put some lipstick on this pig with macros or inline functions, or instead of
int *fieldptr
have achar *fieldptr
, start it at((char*)theMeas) + offset
, and increment it bysizeof(Mea)
each time.If you can't rely on friendly data, then you need at least one branch of some kind (a conditional or a call through a function pointer), just to avoid writing anything in the case where the data is bad. Even to keep it to 1 you probably need a 64k-entry lookup table for 3 cases, which is kind of sparse, so you're probably better off with the conditionals.