C++ Boost多重指数问题

C++ Boost多重指数问题,c++,boost,multi-index,C++,Boost,Multi Index,对不起,我不能在标题上说得更具体了 假设我有一门课 class Foo { public: Foo() { m_bitset.reset(); } void set_i(int i) { m_bitset.set(1); m_i = i; } void set_j(int j) { m_bitset.set(2); m_j = j; } bool i_set() { return

对不起,我不能在标题上说得更具体了

假设我有一门课

class Foo {
public:
    Foo() { m_bitset.reset(); }

    void set_i(int i) {
        m_bitset.set(1);
        m_i = i;
    }

    void set_j(int j) {
        m_bitset.set(2);
        m_j = j;
    }
    bool i_set() { return m_bitset(1); }
    bool j_set() { return m_bitset(2); }
    void clear_i() { m_bitset.reset(1); }
    void clear_j() { m_bitset.reset(2); }
    int get_i() {
        assert(i_set());
        return m_i;
    }
    int get_j() {
        assert(j_set());
        return m_j;
    }

private:
    int m_i, m_j;
    bitset<2> m_bitset;
};
class-Foo{
公众:
Foo(){m_bitset.reset();}
无效集_i(int i){
m_位集.集(1);
m_i=i;
}
无效集_j(int j){
m_位集.集(2);
m_j=j;
}
bool i_集(){返回m_位集(1);}
bool j_集(){返回m_位集(2);}
void clear_i(){m_bitset.reset(1);}
void clear_j(){m_bitset.reset(2);}
int get_i(){
断言(i_set());
返回m_i;
}
int get_j(){
断言(j_集());
返回m_j;
}
私人:
int m_i,m_j;
位集m_位集;
};
现在我想把Foo放入一个multi_索引中

typedef multi_index_container <
    Foo, 
    indexed_by<
        ordered_non_unique<BOOST_MULTI_INDEX_CONST_MEM_FUN( Foo, int, get_i)
        >,
        ordered_non_unique<BOOST_MULTI_INDEX_CONST_MEM_FUN( Foo, int, get_j)
        >
    >
> Foo_set;
typedef多索引容器<
福,
索引<
有序非唯一,
有序非唯一
>
>富集;
我试图找出一种方法,让我的multi_索引对有效值为I或j的Foo进行排序(在复合_键的情况下,或者两者都是),并传递其余的Foo。 因此,我不希望下面的代码被破坏,我只想返回对I有有效值的foo

for (Foo_set::nth_index<1>::type::iterator it = foos.get<1>().begin(); it != foos.get<1>().end(); ++it)
    cout << *it;
for(Foo_set::nth_index::type::iterator it=foos.get().begin();it!=foos.get().end();++it)

通过浏览boost multi_index library文档,我想说的是,你想要的东西在这个库中是不可能实现的。看看它,它似乎只是为所有“维度”上完全可索引的索引元素而设计的。(你可以试着在boost用户邮件列表上询问是否有允许“稀疏”索引维度的黑客。)

无论如何-根据问题的具体性质,您可能可以通过使用boost::optional作为索引类型来解决问题。(尽管我甚至不确定是否可以使用boost::optional进行索引。)

get_I()
get_j()中使用
assert()
当multi_index请求索引的
i
j
值时,功能将导致程序硬停止

听起来您需要空对象模式行为。例如,
m_I
m_j
是采用特殊值表示未设置的数据类型(如果它们是指针,则
Null
指针将用于此目的)。然后您的多索引可以对这些值进行索引,将所有
null
值集中在一起

访问数据时,可以使用筛选空值:

// Predicate for null testing
struct is_not_null {
    bool operator()(const Foo& f) { return f.get_i() != NULL && f.get_j() != NULL; }
};

Foo_set::nth_index<1>::type& idx = foos.get<1>();
BOOST_FOREACH(const Foo& f, idx | filtered(is_not_null())) {
    ;// do something with the non-null Foo's
}
//空测试的谓词
结构不是空的{
bool操作符()(const Foo&f){return f.get_i()!=NULL和&f.get_j()!=NULL;}
};
Foo_集::n_索引::type&idx=foos.get();
BOOST_FOREACH(const Foo&f,idx|filtered(is_not_null())){
;//使用非空的Foo
}

如果您不想污染变量的值空间(即没有可存储的有意义的空值),您还可以考虑将
m_i
m_j
成员转换为的。通过更多的functor包装,您可以创建
的复合索引,这将允许您分别访问set或unset
Foo
。您可以进一步组合索引,将
i
j
与co组合mposite索引看起来像

是的,应该可以通过
boost::optional
进行索引。