如何表示 6 个整数键比作为 6 维数组的索引更好?

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

在我的程序中,一个状态可以由六个整数来唯一标识。每个整数 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);