【问题标题】:static array of which items (structs) know where they are in the array哪些项目(结构)知道它们在数组中的位置的静态数组
【发布时间】:2012-02-23 09:29:30
【问题描述】:

我有一个结构体MyStruct 的静态数组。我需要按索引访问数组,但我还需要每个 MyStruct 知道它的索引是什么。我目前使用以下代码:

enum { INDEX_FOO=0, INDEX_BAR, INDEX_BAZ };
struct MyStruct{ int index; const char* name; /* other data */ };
struct MyStruct values[]={
  { INDEX_FOO, "foo" /* ... */ },
  { INDEX_BAR, "bar" /* ... */ },
  { INDEX_BAZ, "baz" /* ... */ },
};
// requirement: for all i in {0,1,2}: values[i].index==i

但是它会重复枚举索引。有没有办法做到这一点而不必保持枚举和数组同步?

【问题讨论】:

    标签: c arrays enums struct


    【解决方案1】:

    你可以考虑X-macros

    类似:

    blah.x

    X(FOO, "foo")
    X(BAR, "bar")
    X(BAZ, "baz")
    

    ma​​in.c

    #define X(a,b) INDEX_#a,
    enum {
    #include "blah.x"
    };
    #undef X
    
    #define X(a,b) { INDEX_#a, b },
    struct MyStruct values[]={
    #include "blah.x"
    };
    #undef X
    

    【讨论】:

      猜你喜欢
      • 2014-02-22
      • 2015-08-26
      • 1970-01-01
      • 2021-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-08
      • 1970-01-01
      相关资源
      最近更新 更多