【问题标题】:Boost multi_index_container with composite_key and bitwise-and comparison使用复合键和按位与比较来提升 multi_index_container
【发布时间】:2013-04-19 09:52:34
【问题描述】:

我想用 boost multi_index_container 和composite_key 实现这样的目标:

struct LogicalAnd {
    bool operator()(const int& argVal1, const int& argVal2) const {
        return int(argVal1 & argVal2) == argVal1;
    }
};

template<class T, class Enable = void>
class FooContainer;

template <class T>
struct FooContainer<T,typename boost::enable_if<boost::is_base_of<IFoo, T> >::type> {
    typedef multi_index_container<
            boost::shared_ptr<T>,
            indexed_by<
            hashed_non_unique<
            composite_key<
            T,
            const_mem_fun<T,int,&T::getKey1>,
            const_mem_fun<T,int,&T::getKey2>
    >,
    composite_key_equal_to<
    LogicalAnd,
    LogicalAnd
    >
    >
    >
    > shared_ptr_type;
};

知道:

namespace CustomKey {
    typedef enum {
        VAL1 = 0x00000001,
        VAL2 = 0x00000002,
        ALL = 0xFFFFFFFF
    } type;
}

目标是能够执行以下操作:

container.find(boost::make_tuple(CustomKey::VAL1, CustomKey::ALL));

这将允许我检索 LogicalAnd 返回 true 的所有元素。

问题是我无法让我的 LogicalAnd 比较器与我的 multi_index_container 一起工作。

我可以通过在composite_key_equal_to 之前添加composite_key_hash 来构建它:

composite_key_hash<
      boost::hash<int>,
      boost::hash<int>
>

但是 find 操作并没有按预期工作,所以它并没有太大变化......

我搜索了 boost 文档,并尝试了各种实现,但我被大量的信息淹没了......

感谢任何帮助!

【问题讨论】:

  • 如果有帮助,这里有一个测试程序:coliru.stacked-crooked.com/…
  • 至少有人知道吗? :)
  • 至少还在寻找潜在客户?
  • 您实际上并没有说明问题所在。你得到什么构建错误? 如何 find 没有按预期工作?
  • 您好,我在coliru.stacked-crooked.com/… 上面链接了一个测试程序。如前所述,只要我指定composite_key_hash,我就不会收到任何构建错误,但我希望 find 返回一个与我的LogicalAnd::operator 匹配的项目。不幸的是,如链接代码所示,它不起作用,因为find 不返回任何条目。

标签: c++ boost multi-index boost-multi-index


【解决方案1】:

您正在为您的多索引使用 散列

这意味着LogicalAnd 比较器永远不会被调用,除非在正确的哈希桶中找到某些东西。

0x010xFF 不会散列到相同的值 即使 0x01 &amp; 0xFF == 0x01。也就是说,LogicalAnd 会返回 true,但它从未被调用过。

您需要一个不变的哈希函数。 LogicalAnd,我认为这是不可能的。根据设计,大多数哈希函数都应该尽量减少不同键值之间的冲突。

恐怕你需要想出一些不同的索引系统。

【讨论】:

  • 再次感谢您的帮助,既然您已经解释过了,这听起来很合乎逻辑!但随之而来的是我的第二个问题:什么样的索引系统可以帮助我实现这个目标?你有什么想法吗?
  • 您的问题都没有清楚地解释您的目标是什么,它们只是显示了一些没有实现目标的代码。在programmers.stackexchange 上解释你的实际问题可能值得一试。至于允许你想要的那种查找的结构,你可以试试 Trie。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多