gpt4 book ai didi

c++ - boost.multi_index : iterate over an index in reverse order

转载 作者:行者123 更新时间:2023-11-30 05:39:28 25 4
gpt4 key购买 nike

我想知道我们是否可以以相反的顺序迭代 Boost.Multi_Index 容器,类似于 STL 的 vector 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

关于c++ - boost.multi_index : iterate over an index in reverse order,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32339232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com