如何更好地表示 6 个整数键而不是作为 6 维数组的索引?

How to represent 6 integer key better than as indices to a 6-dimensional array?

本文关键字:索引 数组 整数 更好 何更好 地表 表示      更新时间:2023-10-16

在我的程序中,状态可以由六个整数唯一标识。每个整数i满足0 <= i <= 10,并且每个状态都有一个关联的值。我目前正在使用一个 6 维数组来跟踪每个状态值。我将状态值存储在一个数组中,就像state[11][11][11][11][11][11][11]一样,每个值都有 6 个整数作为键。但是,这个数组会非常稀疏,因为我只访问了少数可能的状态。有没有更好的方法来表示状态值的键?

如果你不需要在每个州都有一个值,你可以使用地图

概念代码,完全未经测试。

constexpr int dimension = 6;
using KeyType = std::array<char, dimension>;
int32_t Key(const & KeyType keys) {
int32_t res = 0;
for (auto key : keys) {
res <<= 4;
res += key;
}
return res;
}
void Key2Array(int32_t keyValue, KeyType& keys) {
int idx = dimension-1;
for (auto& key : keys) {
keys[idx--] = keyValue&0x16;
keyValue >>= 4;
}
}
std::map<int32_t, value> states;
states[Key({1,2,3,4,5,6}] = 42;
KeyType key;
Key2Array(0x123456, key);