迭代一个boost multi_index

时间:2015-12-16 21:43:08

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

SO。我正在使用igraph对象,我想按特定顺序迭代顶点。顺序由称为“值”的顶点属性确定,我想操作从最高到最低。 igraph可以以顶点id顺序提供所有值作为igraph_vector_t。如果顶点17具有最高值,我想先对它进行操作。

搜索完SO后,我开始研究C ++ boost multi_index。这是一个支持结构:

struct indexed_vertex {
    igraph_integer_t vid;
    igraph_real_t value;
    indexed_vertex(igraph_integer_t vid, igraph_real_t value):vid(vid),value(value){}

    bool operator<(const indexed_vertex &vertex) const {
        return value<vertex.value;
    }
};

我创建了以下索引对象:

typedef boost::multi_index::multi_index_container<
        indexed_vertex,
        boost::multi_index::indexed_by<
                boost::multi_index::hashed_unique<
                    boost::multi_index::member<indexed_vertex, igraph_integer_t, &indexed_vertex::vid>
                >,
                boost::multi_index::ordered_non_unique<
                        boost::multi_index::member<indexed_vertex, igraph_real_t, &indexed_vertex::value>
                >
        >
> indexed_vertex_set;

我的下一个技巧是按降序访问顶点。我试过这个(来自docs),但几乎立即失败(嘿!快失败吧?)

indexed_vertex_set ivs;
indexed_vertex_set::nth_index<1>::type::iterator it = ivs.get<1>();

错误

 error: no viable conversion from 'typename nth_index<1>::type' (aka 'boost::multi_index::detail::ordered_index<boost::multi_index::member<indexed_vertex, double, &indexed_vertex::value>, std::__1::less<double>, boost::multi_index::detail::nth_layer<2, indexed_vertex, boost::multi_index::indexed_by<boost::multi_index::hashed_unique<boost::multi_index::member<indexed_vertex, int, &indexed_vertex::vid>, mpl_::na, mpl_::na, mpl_::na>, boost::multi_index::ordered_non_unique<boost::multi_index::member<indexed_vertex, double, &indexed_vertex::value>, mpl_::na, mpl_::na>, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na>, std::__1::allocator<indexed_vertex> >, boost::mpl::vector0<mpl_::na>, boost::multi_index::detail::ordered_non_unique_tag, boost::multi_index::detail::null_augment_policy>') to 'indexed_vertex_set::nth_index<1>::type::iterator' (aka 'bidir_node_iterator<node_type>')
    indexed_vertex_set::nth_index<1>::type::iterator it = ivs.get<1>();

我尝试过其他一些变种,但不断回到这个错误。我很感激建议。我以前没有使用过multi_index,所以我期待我从根本上误解了范围。

奖金问题

因为这是假期,我会指出我的下一个任务是做一些像

这样的事情
for (vertex in iterator) {
   get-vertex-id();
   get-vertex-value();
   look-up-vertex-and-modify();
}

所以,如果你感到慷慨,我也很感激那里的指导。

2 个答案:

答案 0 :(得分:3)

ivs.get<1>()为您提供索引,而不是迭代器。您需要在该索引上调用begin()end()和其他方法来获取迭代器(就像在容器上一样)。您最好使用typedef

indexed_vertex_set ivs;
typedef indexed_vertex_set::nth_index<1>::type sorted_index;
sorted_index &idx = ivs.get<1>();
for( sorted_index::iterator it = idx.begin(); it != idx.end(); ++it ) {
    it->vid = 123; // getting access to fields
}

答案 1 :(得分:2)

使用C ++ 11,这可能会更简单:

mic_structure mic;

// ...

for (auto & it : mic.get<0>()) {
    // do something with iterator
}
相关问题