从 Boost 多索引迭代器获取数字索引

我正在存储一堆以下内容

I'm storing a bunch of the following

struct Article {
    std::string title;
    unsigned db_id;     // id field in MediaWiki database dump
};

在 Boost.MultiIndex 容器中,定义为

in a Boost.MultiIndex container, defined as

typedef boost::multi_index_container<
    Article,
    indexed_by<
        random_access<>,
        hashed_unique<tag<by_db_id>,
                      member<Article, unsigned, &Article::db_id> >,
        hashed_unique<tag<by_title>,
                      member<Article, std::string, &Article::title> >
    >
> ArticleSet;

现在我有两个迭代器,一个来自 index<by_title>,一个来自 index<by_id>.在不向 struct Article 添加数据成员的情况下,将这些索引转换为容器的随机访问部分的最简单方法是什么?

Now I've got two iterators, one from index<by_title> and one from index<by_id>. What is the easiest way to transform these to indexes into the random access part of the container, without adding a data member to struct Article?

推荐答案

每个索引都支持使用 iterator_to.如果您在一个索引中已经有一个指向目标值的迭代器,则可以使用它来转换为另一个索引中的迭代器.

Every index supports generation of an iterator by value using iterator_to. If you already have an iterator to the target value in one index, you could use this to convert to an iterator in another index.

iterator       iterator_to(const value_type& x);
const_iterator iterator_to(const value_type& x)const;

对于转换为索引,您可以遵循 random_access_index.hpp 中的模型:

For conversion to index you can likely follow the model in random_access_index.hpp:

  iterator erase(iterator first,iterator last)
  {
    BOOST_MULTI_INDEX_CHECK_VALID_ITERATOR(first);
    BOOST_MULTI_INDEX_CHECK_VALID_ITERATOR(last);
    BOOST_MULTI_INDEX_CHECK_IS_OWNER(first,*this);
    BOOST_MULTI_INDEX_CHECK_IS_OWNER(last,*this);
    BOOST_MULTI_INDEX_CHECK_VALID_RANGE(first,last);
    BOOST_MULTI_INDEX_RND_INDEX_CHECK_INVARIANT;
    difference_type n=last-first;
    relocate(end(),first,last);
    while(n--)pop_back();
    return last;
  }

相关文章