【问题标题】:Container Using std::set with Multiple Compare Criteria使用带有多个比较标准的 std::set 的容器
【发布时间】:2018-08-03 12:04:02
【问题描述】:

我正在尝试编写一个包含两个 std::sets 的容器,这些 std::sets 使用不同的比较器类具有相同的元素。这是我的看法,经过简化:

struct Element
{
    // foo and bar are immutable to prevent messing set order up.
    FooStruct const foo;
    BarStruct const bar;
    int someVar;

    Element(FooStruct foo);
    Element(BarStruct bar);
};

class CriterionFoo
{
    // Sorts according to member foo.
    bool operator()(Element* const& arg0, Element* const& arg1);
};

class CriterionBar
{
    // Sorts according to member bar.
    bool operator()(Element* const& arg0, Element* const& arg1);
};

class ElementContainer
{
    typedef std::set<Element*, CriterionFoo> FooSortedSet;
    typedef std::set<Element*, CriterionBar> BarSortedSet;

    FooSortedSet fooSortedSet;
    BarSortedSet barSortedSet;

    // fooSortedSet.find(&Element(myFoo))
    Element* findElement(FooStruct myFoo);
    // barSortedSet.find(&Element(myBar))
    Element* findElement(BarStruct myBar);

    // Inserts in both sets.
    void insert(Element* element);

    // Enter total alienation and existential crisis...
    void erase(BarStruct myBar);
    void erase(FooStruct myFoo);
};

我想要实现的只是创建一个集合包装器,它可以在 log(n) 复杂度中找到具有两个不同搜索条件的成员。 ElementContainer::erase 方法可以很容易地为任一标准找到 [Foo|Bar]SortedSet::iterator,但无论如何我都必须天真地遍历另一个(这几乎超过了整点)。话又说回来,我可以将[Foo|Bar]SortedSet::const_iterator 引用放入Element 结构中,然后一步即可到达另一组中的相应迭代器,但这感觉有点矫枉过正。

好吧,我不可能是第一个遇到这种情况的人。是否有任何既定方法可以使用多个标准来保持一组元素易于导航?尤其是在没有过度设计狂热的情况下?

【问题讨论】:

标签: c++ data-structures stl


【解决方案1】:

首先,您需要异构查找:能够找到具有给定BarStruct 值myBar 的Element,而无需构造一个虚拟Element(myBar)。这可以通过将以下operator() 重载添加到CriterionBar(等效于CriterionFoo)来实现:

bool operator()(Element* const& lhs, BarStruct const& rhs) const;
bool operator()(BarStruct const& lhs, Element* const& rhs) const;

注意:您的比较运算符必须是const 成员函数!

此外,您 need to add 和 is_transparent 使集合考虑这些额外的比较选项(并将相应的重载添加到例如 find)。例如:

using is_transparent = void;

这不是绝对必要的,但比你目前正在做的虚拟 Element 事情要好得多。

在两个O(log(N)) 操作中从两个集合中删除的实际步骤很简单:

void erase(FooStruct myFoo)
{
  auto fooIt = fooSortedSet.find(myFoo);
  Element* elementToErase = *fooIt;
  auto barIt = barSortedSet.find(elementToErase);

  fooSortedSet.erase(fooIt);
  barSortedSet.erase(barIt);
}

【讨论】:

  • 不错的运算符重载技巧,我会考虑到这一点。这两个集合都没有将Element* 类型作为它们的键值,但我不知道如何使用该引用来find。编辑:你可能有一点,我想我需要头脑清醒地考虑一下。
  • @corsel 请注意我此后所做的编辑。特别是,is_transparent 需要它才能工作。
  • @corsel 你是什么意思“集合不以Element* 作为键值”?您可以比较/区分/查找元素,这就是集合的重点......
  • 是的,这是一个混乱的时刻 :) 我想我可以将此标记为答案。回答完之后好像很明显。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-13
  • 2010-11-06
  • 2017-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-15
相关资源
最近更新 更多