c++ - 在 map/unordered_map 中使用多个键(多维)

标签 c++ dictionary hashmap

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 复制实现.

Live example

关于c++ - 在 map/unordered_map 中使用多个键(多维),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22572396/

相关文章:

rust - 如何接受带有任何散列算法的 Rust HashMap?

c++ - 如何在不创建新对象的情况下引用 substr?

python - 字典键可以强制按特定顺序排列吗?

c++ - 在 C++ 中用私有(private)函数覆盖公共(public)虚函数

c++ - C++ 概念可以用于在 C++ 中实现混合类型 min 和 max 吗?

c# - 当我调用 DLL 中的函数时会发生什么

python键值对

python - dict_values 到 python 中的字符串

Java:HashMap<String,String> 存储与键和值相同的值。

c++ - MFC 发送消息中的对象