【发布时间】: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 结构中,然后一步即可到达另一组中的相应迭代器,但这感觉有点矫枉过正。
好吧,我不可能是第一个遇到这种情况的人。是否有任何既定方法可以使用多个标准来保持一组元素易于导航?尤其是在没有过度设计狂热的情况下?
【问题讨论】:
-
“我必须天真地遍历另一个”,在删除之前检索元素,这样您就可以同时获得
Foo和Bar成员的 log(n)搜索...
标签: c++ data-structures stl