c++ - 如何在 boost::unordered_map 中为键使用自定义类型?

标签 c++ boost hashmap unordered-map int128

我现在正在项目中使用 Boost 的 HashMap 实现,并且我正在尝试为键实现自定义类型。我有四个无符号整数,我想将它们组合成一个 128 位数据类型以用作键。

我创建了一个包含四个元素的 32 位整数数组的结构,用作我的存储。老实说,我不确定 Boost 的 HashMap 是如何工作的,所以我不确定我在这里做什么,但我按照 Boost 文档(http://www.boost.org/doc/libs/1_37_0/doc/html/hash/custom.html)扩展了 boost::hash,并创建了一个哈希函数,以及自定义比较运算符。

我在标题中定义了这个自定义类型。这是我的代码:

#ifndef INT128_H_
#define INT128_H_

// Custom 128-bit datatype used to store and compare the results of a weakened hash operation.
struct int128
{
    unsigned int storage[4];

    /* Assignment operation that takes a 32-bit integer array of four elements.
    This makes assignment of values a shorter and less painful operation. */
    void operator=(const unsigned int input[4])
    {
        for(int i = 0; i < 4; i++)
            storage[i] = input[i];
    }
};

bool operator==(int128 const &o1, int128 const &o2)
{
    if(o1.storage[0] == o2.storage[0] && o1.storage[1] == o2.storage[1] && 
       o1.storage[2] == o2.storage[2] && o1.storage[3] == o2.storage[3])
        return true;

    return false;
}

// Hash function to make int128 work with boost::hash.
std::size_t hash_value(int128 const &input)
{
    boost::hash<unsigned long long> hasher;
    unsigned long long hashVal = input.storage[0];

    for(int i = 1; i < 3; i++)
    {
        hashVal *= 37;
        hashVal += input.storage[1];
    }

    return hasher(hashVal);
}

#endif

现在,当我在 Boost 的无序映射中实际使用此类型时,我的代码可以编译,但无法链接。链接器声称我在多个目标文件中多次定义了一个符号。我真的很想让我的 128 位类型与这张 map 一起工作。关于我搞砸了什么的任何提示,或者更好的方法吗?

最佳答案

unordered-map 的参与对于您遇到的问题几乎是偶然的。真正的问题是您在每个包含上述 header 的文件中定义了 hash_valueoperator==

您可以通过以下任一方法解决此问题:

  1. 将它们定义为内联函数
  2. 只需在标题中声明它们

如果你选择后者(这是你通常想要的),你会将这些函数的定义移动到一个 .cpp 文件中(或者你用于 C++ 源文件的任何扩展名) .然后,您将编译该文件,并将生成的对象与使用 int128 类型的其他代码链接起来。

编辑:您仍然可以使比较更清晰,例如:

bool operator==(int128 const &o1, int128 const &o2)
{
    return o1.storage[0] == o2.storage[0] && o1.storage[1] == o2.storage[1] && 
           o1.storage[2] == o2.storage[2] && o1.storage[3] == o2.storage[3]);
}

关于c++ - 如何在 boost::unordered_map 中为键使用自定义类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1829639/

相关文章:

c++ - 大条目的慢 std::map

c++ - 使用复杂类型输入的 WSDLPull

c++ - 如何在这里创建一个循环? C++

c++ - 如何从其他目录树将源文件包含到 Bool.Test 用例中?

java - Jackson 将 YAML 文件反序列化为 Map(没有自定义反序列化器)

java - 4 键值HashMap?大批?最佳方法?

c++ - 如何查看c++中小于运算符的函数定义

c++ - 乘以可变数量的参数

c++ - 修改具有 hashed_non_unique 键的 Boost Multi-Index Map 中的键范围

c++ - 从 C++11 中的容器元组中提取 value_type 的元组