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++ 中正确使用命名空间? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- c++ STL设置差异 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
