c++ - 获取 boost::multi_index 容器元素的等级

标签 c++ boost boost-multi-index

下面的代码显示了一个按序列和顺序索引的 multi_index 容器。

在我的用例中,元素将主要通过索引搜索,如果存在,则获取下一个元素(按顺序)。

我的问题是,如何获得获得的下一个元素的排名(按顺序)?

#include <iostream>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/ranked_index.hpp>
#include <boost/multi_index/identity.hpp>

using namespace boost::multi_index;

typedef multi_index_container <
    int
  , indexed_by<
        sequenced<>
      , ordered_non_unique<identity<int>>
      , ranked_non_unique<identity<int>>
    >
> Ints;

int main() {
    Ints ints;

    auto & sequence=ints.get<0>();
    auto & order=ints.get<1>();

    sequence.push_back(2);
    sequence.push_back(-1);
    sequence.push_back(5);
    sequence.push_back(6);

    auto it = order.find(2);
    if (it!=order.end()) {
        std::cout
            << "next to "
            << *it
            << " by sequence is "
            << *(++(ints.project<0>(it)))
            << std::endl
        ;
        std::cout
            << "next to "
            << *it
            << " by order is "
            << *(++(ints.project<1>(it))) //++it is good too
            << std::endl
        ;
        std::cout
            << "rank of next by sequence is "
            // << ??? ints.rank<???>(???)
            << std::endl
        ;
        std::cout
            << "rank of next by order is "
            // << ??? ints.rank<???>(???)
            << std::endl
        ;
    }
}

最佳答案

@sehe 的回答完全有效,但在线性时间内运行。如果您想要更好的性能,请考虑将索引 #0 定义为 random_access 并将 #1 定义为 ranked_non_unique(索引 #2 是多余的):

typedef multi_index_container <
    int
  , indexed_by<
        random_access<>
      , ranked_non_unique<identity<int>>
    >
> Ints;

这样你就可以写:

std::cout
    << "rank of next by sequence is "
    << ints.project<0>(it)-sequence.begin()+1 // O(1)
    << std::endl
;
std::cout
    << "rank of next by order is "
    << order.rank(it)+1 // O(log n)
    << std::endl
;

关于c++ - 获取 boost::multi_index 容器元素的等级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33874515/

相关文章:

c++ - 如何在 C++ 中分配在 Python 中创建的对象?

c++ - 这是 boost::iterator_facade 的 boost::range_detail::demote_iterator_traversal_tag 中的错误吗?

c++ - 从 boost multi_index 数组中 move 元素

c++ - String-Interning 使用哪个容器

c++ - 在类方法中使用 new 运算符动态分配内存的生命周期和范围是多少?

成员变量的 C++ 偏移量?

c++ - 在卷 DICOM 图像上设置 vtkLookupTable

c++ - 如何划分boost::optional<double>?

c++ - boost::multi_index 如何与成员函数一起工作?

c++ - 如何将 GCC 类传递给 MSVC dll?