boost.multi_index:以相反的顺序遍历索引

boost.multi_index: iterate over an index in reverse order

我想知道我们是否可以以相反的顺序迭代 Boost.Multi_Index 容器,类似于 STL 的向量 rbegin()rend()

以下代码大部分借鉴自here。在遍历 legs_index(最后几行)并打印动物名称时,动物名称会根据腿数按升序显示。我需要按降序执行相同的操作。

知道怎么做吗?

谢谢!

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/random_access_index.hpp>
#include <boost/multi_index/member.hpp>
#include <string>
#include <iostream>

using namespace boost::multi_index;

struct animal
{
  std::string name;
  int legs;
};

typedef multi_index_container<
  animal,
  indexed_by<
    sequenced<>,
    ordered_non_unique<
      member<
        animal, int, &animal::legs
      >
    >,
    random_access<>
  >
> animal_multi;

int main()
{
  animal_multi animals;

  animals.insert({"cat", 4});
  animals.insert({"shark", 0});
  animals.insert({"spider", 8});

  auto &legs_index = animals.get<1>();
  auto it = legs_index.begin();
  auto end = legs_index.end();
  for (; it != end; ++it)
    std::cout << it->name << '\n';
}

问题出在插入调用上:

animals.insert(animals.end(), animal_multi::value_type {"cat", 4});
animals.insert(animals.end(), animal_multi::value_type {"shark", 0});
animals.insert(animals.end(), animal_multi::value_type {"spider", 8});

现在,只需使用反向迭代器:

auto &legs_index = animals.get<1>();
auto it = legs_index.rbegin();
auto end = legs_index.rend();
for (; it != end; ++it)
  std::cout << it->name << '\n';

Live On Coliru

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/random_access_index.hpp>
#include <boost/multi_index/member.hpp>
#include <string>
#include <iostream>

using namespace boost::multi_index;

struct animal
{
  std::string name;
  int legs;
};

typedef multi_index_container<
  animal,
  indexed_by<
    sequenced<>,
    ordered_non_unique<
      member<
        animal, int, &animal::legs
      >
    >,
    random_access<>
  >
> animal_multi;

int main()
{
  animal_multi animals;

  animals.insert(animals.end(), animal_multi::value_type {"cat", 4});
  animals.insert(animals.end(), animal_multi::value_type {"shark", 0});
  animals.insert(animals.end(), animal_multi::value_type {"spider", 8});

  auto &legs_index = animals.get<1>();
  auto it = legs_index.rbegin();
  auto end = legs_index.rend();
  for (; it != end; ++it)
    std::cout << it->name << '\n';
}

版画

spider
cat
shark