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

标签 c++ string set unordered-set

我想填充一个集合,其中每个项目都是 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));

没用。为什么?错误似乎是,除其他外,

The C++ Standard doesn't provide a hash for this type.

(对于 unordered_set 案例)。

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

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

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

最佳答案

我建议使用 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"));

关于c++ - 如何填充项目为 8 个字符的集合? (std::set<字符[8]>),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48139731/

相关文章:

c++ - Boost ASIO 服务器 - 检测空闲连接

python - 是否有一种始终以 0.x 开头的 float 字符串格式?

javascript - 在 JavaScript 中生成随机字符串/字符

c++ - 更新 : Memory Location being outputted instead of desired string

php - 寻找最好的 PHP 嵌套集类(不包括 PEAR 类)

java - JAVA 中的 this.set(charHere)

c++ - 如何将元素添加到元组 vector

c++ - 初始化一个指向 char 数组的指针

c++ - 将字符串中的所有单词放入多个字符串中 C++

C++ 在已创建对象时设置 emplace 与 insert