c++ - 将 Boost multi_index 用于组合键

标签 c++ boost c++14

如何使用 Boost multi_index 将三个键组合成一个查询表达式?考虑以下索引结构:

struct indexItems {
    uint64_t x; // assume non-unique index
    std::string y; // assume unique within x
    std::string z; // assume unique within y
};

假设我想使用二进制 AND 运算符查询项目:x=1 AND y="a"AND z="s"。我该怎么做?

所有查询和插入都将使用 x+y+z 的组合来插入、更新和删除 multi_index 中的项目。除此之外,我需要遍历按 x 排序的 y 和 z。

到目前为止,我找到的示例仅处理单个索引。

最佳答案

您实际上不需要为此使用 multi_index_container。你可以这样做:

inline bool operator<(const indexItems& l, const indexItems& r) {
    return std::tie(l.x, l.y, l.z) < std::tie(r.x, r.y, r.z);
}

inline bool operator==(const indexItems& l, const indexItems& r) {
    return std::tie(l.x, l.y, l.z) == std::tie(r.x, r.y, r.z);
}

std::set<indexItems> items; // or use map with any second type

现在您有一组数据,先按 x,然后按 y,然后按 z 排序。查询 x=1 AND y="a"AND z="s":

items.find(indexItems{1, "a", "s"});

遍历按 x 排序的所有值(其次按 y 和 z 排序,虽然这实际上不是必需的,但它也没有坏处):

for (const indexItems& item : items)
    // ...

作为奖励,如果您想找到 x 某个范围内的所有值:

auto it = items.lower_bound(indexItems{100});
auto end = items.upper_bound(indexItems{105});
for (; it != end; ++it)
    // ...

关于c++ - 将 Boost multi_index 用于组合键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58142512/

相关文章:

c++ - 棘手的 undefined reference 错误

c++ - 使用 C++ 以编程方式将新盘符分配给现有驱动器

c++ - Visual C++ 中的位域问题

C++ QueryPerformanceCounter 比 sleep 更准确?

c++ - 我应该以什么顺序读取MSVC编译器的生成错误?

c++ - 什么是 boost::asio::write 保证(ACK,校验和)?

c++ - boost::any 违反了 Liskov 替换原则

c++ - 多线程:apache 可移植运行时与 boost::thread?

c++ - 如何创建双 RowMajor 的动态大小的 Eigen::Matrix?

c++ - 模板函数的部分 typedef (`using` )