稀疏初始化静态数组 [英] Initialize sparse static array

查看:125
本文介绍了稀疏初始化静态数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要初始化静态数组。并不是所有的值是连续的。

像这样工作正常顺序排列:

 类Foo {  上市:  静态为const char *名称[];}为const char *美孚::名[] = {太阳,月亮};

我怎样才能在阵列中的任意位置赋值?我需要做的是这样的(伪code):

 为const char *美孚::名[] = {67:太阳报,68:月亮};

该数组决不会比255更大;指数来自字节值。


我发现的rel=\"nofollow\">一部分如果有人给出了类似我想要什么东西的例子,但我无法得到任何这样的工作。

 类型的数组[SIZE] = {[SIZE-4] = 1,2,3,4};


这里有一个老派的做法:

 类NameArray {
  上市:
    NameArray()
    {
      数组[67] =太阳报;
      数组[68] =月亮;
    }    为const char *运算符[](为size_t指数)常量
    {
      断言(指数< 256);
      返回数组[索引]
    }
  私人的:
    为const char *数组[256];
};类Foo {
  上市:
    静态NameArray名称;
};NameArray富::名称;

通过包装数组中的一类,可以确保它得到与你想要的值构建。你也可以做边界检查。

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" };

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};

解决方案

Here's one old-school approach:

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.

这篇关于稀疏初始化静态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆