Boost::unordered_set的char16_t字符串

boost::unordered_set of char16_t strings

本文关键字:字符串 char16 set unordered Boost      更新时间:2023-10-16

为什么

#include <string>
#include <boost/unordered_set.hpp>
int main()
{    
    typedef boost::unordered_set<std::string> unordered_set;
    unordered_set animals;
    animals.emplace("cat");
    animals.emplace("shark");
    animals.emplace("spider");
    return 0;
}

和后面的工作导致太多的编译错误。

#include <string>
#include <boost/unordered_set.hpp>
int main()
{    
    typedef boost::unordered_set<std::u16string> unordered_set;
    unordered_set animals;
    animals.emplace("cat");
    animals.emplace("shark");
    animals.emplace("spider");
    return 0;
}

还有,这个问题的解决方案是什么?我需要像这里提到的那样在函数对象中编写自己的hash_functionoperator==吗?

operator==不是一个问题,因为它已经在标准库中定义了。但是,哈希函数必须从标准库提供的std::u16stringstd::hash专门化中进行调整,这将适用于std::unordered_*容器,但不适用于Boost的容器。

一种解决方案可能是按以下方式定义哈希函数:

std::size_t hash_value(std::u16string const &s) {
    return std::hash<std::u16string>{}(s);
}

这个包装器将为您提供一个已经编写的逻辑包装,以很好地与Boost一起工作。

最后,让我提醒你在c++ 11标准库中等效的std::unordered_set容器的可用性,如果你不知道的话。