我想知道我们是否可以以相反的顺序迭代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';
}
答案 0 :(得分:1)
问题在于插入调用:
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