Ask a question Multi_Index

Sorry, I could not be more specific in the title.

Say I have a Foo class

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;
};

And now I want to put Foo in multi_index.

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;

What I'm trying to figure out is a way for my multi_index to sort Foo, which has valid values ​​of me or j (or both in the case of compound_key and passed to the rest. So I don’t want the code below to explode, I just want only return foos that have valid values ​​for i.

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

- boost multi_index , , , . rationale, , , "". (, , - , "" .)

- , boost:: optional . ( , boost:: optional.)

+1

assert() get_i() get_j() , multi_index i j .

, , . m_i m_j - , , , ( , NULL ). , NULL.

boost:: range, :

// 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
}

(.. , ), m_i m_j boost:: optional. <bool, int>, unset Foo . i j , <bool, bool, int, int>.

+1

Source: https://habr.com/ru/post/1759713/


All Articles