初始化稀疏静态数组

2022-01-19 00:00:00 arrays initialization static c++

我需要初始化一个静态数组.并非所有值都是连续的.

I need to initialize a static array. Not all of the values are sequential.

这样的东西对顺序数组很有效:

Something like this works fine for a sequential array:

class Foo {

  public:

  static const char * name[];

}

const char * Foo::name[] = { "Sun", "Moon" };

如何在数组中的任意位置赋值?我需要做这样的事情(伪代码):

How can I assign values at arbitrary positions in the array? I need to do something like this (pseudocode):

const char * Foo::name[] = { 67: "Sun", 68: "Moon" };

数组永远不会大于 255;索引来自字节值.

The array will never be bigger than 255; the indices come from byte values.

我发现 部分线程有人举了一个与我想要的类似的例子,但我无法让这样的事情起作用.

I found part of a thread where someone gives an example of something similar to what I want, but I couldn't get anything like this to work.

type array[SIZE] = {[SIZE-4]=1, 2, 3, 4};

推荐答案

这是一种老派的方法:

class NameArray {
  public:
    NameArray()
    {
      array[67] = "Sun";
      array[68] = "Moon";
    }

    const char *operator[](size_t index) const
    {
      assert(index<256);
      return array[index];
    }


  private:
    const char * array[256];
};

class Foo {
  public:
    static NameArray name;
};

NameArray Foo::name;

通过将数组包装在一个类中,您可以确保使用您想要的值构造它.你也可以做边界检查.

By wrapping the array in a class, you can make sure it gets constructed with the values that you want. You can also do bounds checking.

相关文章