如何填充项目为 8 个字符的集合?(std::set<char [8]>)

How to fill a set where items are 8 char? (std::set<char [8]>)

本文关键字:set lt char gt std 项目 填充 何填充 集合 字符      更新时间:2023-10-16

我想填写一个集合,其中每个项目是 8 个字节(可以是 8 个可读字符或二进制数据(。看来

std::unordered_set<char [8]> d;
d.insert("abcdefgh");
std::set<char [8]> d2;
d2.insert("abcdefgh");
std::string s = "Hello this is a string, the first 16 char will be inserted in the set";
d2.insert(s.substr(0,16));

不行。为什么?错误似乎是,除其他外,

C++标准不为此类型提供哈希。

(对于unordered_set情况(。

有没有办法制作一组 8 字节的项目?

注意:我想避免std::unordered_set<std::string> d,因为这里每个项目实际上是 8 个数据字节,我想保持简单和小(集合将有数百万个项目(。我想避免std::string结构本身/指针等使用的另一层内存。

注意2:我使用的是set/unordered_set,而不是向量或其他任何东西,因为我想超快的成员资格查找。

我建议改用std::array<char, 8>;

您必须定义哈希器:

struct hash_char_8 {
    std::size_t operator()(std::array<char, 8> arr) {
    }
}

或者只是使用std::set.

您需要将文字转换为数组:

#include <algorithm>
    // std::copy
std::array<char, 8> to_char_8(char const literal[9]) {
    std::array<char, 8> a;
    std::copy(literal, literal + 8, a.begin());
    return a;
}

使用它的代码:

std::unordered_set<std::array<char, 8>, hash_char_8> d;
d.insert(to_char_8("abcdefgh"));