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.
这篇关于初始化稀疏静态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:初始化稀疏静态数组


基础教程推荐
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01