Consier 我有一些水桶 ( vector<float>
)。我需要根据一些索引访问这个桶。示例:
int indexX, indexY, indexZ, indexW;
因此,当一个新点到达时,我需要将该点放入正确的桶中。现在我正在做这样的事情:
// X Y Z W => Bucket
unordered_map<int, unordered_map<int, unordered_map<int, unordered_map<int, vector<float>>>>> indexedTable;
// New point arrives and I put it in the right bucket:
indexedTable[indexX][indexY][indexZ][indexW].push_back(myValue);
但我发现这非常丑陋,遗憾的是它也非常慢。比如访问1700点,需要0.56秒,太慢了。
在不使用 Boost 的情况下,是否有更好/更快的替代方案?
请注意,我需要的这种数据结构与稀疏矩阵(多维)相当,因为很少有“桶”会被填满。
最佳答案
您可以使用unordered_map
而不是使用这个4 深的怪物。用struct
包含 4 个索引作为键,以及 vector<float>
作为值类型。为结构提供相等比较器和哈希函数,您就可以开始工作了。
struct indices
{
int indexX, indexY, indexZ, indexW;
bool operator==(indices const& other) const
{
return std::tie(indexX, indexY, indexZ, indexW) ==
std::tie(other.indexX, other.indexY, other.indexZ, other.indexW);
}
};
struct indices_hash
{
std::size_t operator()(indices const& i) const
{
std::size_t seed = 0;
boost::hash_combine(seed, i.indexX);
boost::hash_combine(seed, i.indexY);
boost::hash_combine(seed, i.indexZ);
boost::hash_combine(seed, i.indexW);
return seed;
}
};
std::unordered_map<indices, std::vector<float>, indices_hash> m;
既然你不想使用 Boost,要么想出你自己的 hash_combine
替代或从 here 复制实现.
关于c++ - 在 map/unordered_map 中使用多个键(多维),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22572396/