我有一个 boost::multi_index 容器。有人能告诉我如何根据某个键检索一系列迭代器吗?经过几个小时的搜索后,我得到了 lower_bound 或 upper_bound 应该可以解决问题的想法,但我仍然没有例子。在下面的示例中,我想获取价格在 22 到 24 之间的所有迭代器。非常感谢。
struct order
{
unsigned int id;
unsigned int quantity;
double price;
order(unsigned int id_, unsigned int quantity_, double price_)
:id(id_), quantity(quantity_), price(price_){}
}
typedef multi_index_container<
order,
indexed_by<
ordered_unique<
tag<id>, BOOST_MULTI_INDEX_MEMBER(order, unsigned int, id),
std::greater<unsigned int>>,
ordered_non_unique<
tag<price>,BOOST_MULTI_INDEX_MEMBER(order ,double, price)>
>
> order_multi;
int main()
{
order_multi order_book;
order_book.insert(order(/*id=*/0, /*quantity=*/10, /*price=*/20));
order_book.insert(order(/*id=*/1, /*quantity=*/11, /*price=*/21));
order_book.insert(order(/*id=*/3, /*quantity=*/12, /*price=*/22));
order_book.insert(order(/*id=*/2, /*quantity=*/1, /*price=*/22));
order_book.insert(order(/*id=*/4, /*quantity=*/1, /*price=*/23));
order_book.insert(order(/*id=*/5, /*quantity=*/1, /*price=*/24));
order_book.insert(order(/*id=*/6, /*quantity=*/1, /*price=*/24));
order_book.insert(order(/*id=*/7, /*quantity=*/1, /*price=*/26));
}
最佳答案
您要查找的范围是 [lower_bound(22)
,upper_bound(24)
),即:
auto first=order_book.get<price>().lower_bound(22);
auto last=order_book.get<price>().upper_bound(24);
for(;first!=last;++first)std::cout<<first->id<<" "; // prints 3 2 4 5 6
如果您发现难以确定何时需要使用 lower_
或 upper_bound
,可以使用 range
member function这可能更容易正确(并且稍微快一些):
auto range=order_book.get<price>().range(
[](double p){return p>=22;}, // "left" condition
[](double p){return p<=24;}); // "right" condition
for(;range.first!=range.second;++range.first)std::cout<<range.first->id<<" ";
前提是您使用 C++11 并具有 lambda 函数。您还可以在 C++03 中使用 range
而无需 native lambda 函数,但随后您必须求助于 Boost.Lambda或者手动编写 range
接受的仿函数,这两个选项可能都太麻烦了。
关于c++ - 如何查找带有键的所有匹配 boost::multi_index ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37076458/