在 C++ 中指定数组声明中的元素位置
在 C 中,在进行数组声明时指定元素位置通常非常有帮助。
例如:
int appliance_id_from_mode[] = {
[MASTER] = 0,
[SLAVE] = 1
};
这个声明逐字似乎在 c++ (或至少 g++ )中不起作用,有等效的吗?
In C it is often very helpful to specify the element position when doing an array declaration.
eg:
int appliance_id_from_mode[] = {
[MASTER] = 0,
[SLAVE] = 1
};
This declaration verbatim does not seem to work in c++ ( or at least g++ ), is there any equivalent?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这看起来像是地图的用途?
this looks like a use for map?
C++ 不支持这一点,您可以将其扩展为等效的声明:
不太漂亮...但应该可以。如果 MASTER 和 SLAVE 是枚举的值,您可以创建第三个 NUMBER_OF_MODES 条目,这将避免在数组大小中进行繁琐的大小计算...
That is not supported in C++, you can expand that into the equivalent declarations:
Not quite pretty... but should work. If MASTER and SLAVE are values of an enum, you can create a third NUMBER_OF_MODES entry that will avoid the need for the cumbersome size calculation in the array size...
不要认为标准 C++ 中(至少)存在这种等价语言。然而,为了提高可读性,您肯定可以使用
/*comments*/
来帮忙!Don't think that such language equivalent exists (at least) in standard C++. However for readability you can surely do a favor using
/*comments*/
!C# 有这样的奢侈。默认情况下,我们(C++ 程序员)在 C++ 下没有那么奢侈。 IMO,只需接受它并承受痛苦,而不是通过使用其他方式而不是普通数组来提供令人困惑的代码。
C# has such kind of luxury. By default we (C++ programmers) doesn't have that luxury under C++. IMO, just accept it and take the pain rather than providing confusing code by using other means instead of plain arrays.