Initialize sparse static array(初始化稀疏静态数组)
问题描述
我需要初始化一个静态数组.并非所有值都是连续的.
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.
这篇关于初始化稀疏静态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:初始化稀疏静态数组
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
