我们需要一个容器,在附加一个新元素时保持元素按元素的优先级排序,该元素能够在给定id的情况下检索元素。
(优先级队列的问题在于它不能让你根据id而不是优先级检索元素)
感谢
答案 0 :(得分:7)
boost multi index containers使您能够对优先级进行排序视图,并对ID进行排序视图。
一个小例子:
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/member.hpp>
#include <iostream>
#include <vector>
#include <cstddef>
#include <iterator>
struct elem {
std::size_t id;
int priority;
};
int main()
{
using namespace boost::multi_index;
typedef multi_index_container<
elem,
indexed_by<
ordered_unique<member<elem,std::size_t,&elem::id> >,
ordered_non_unique<member<elem,int,&elem::priority> >
>
> elem_container;
// just for show
std::vector<elem> elems =
{{0, 25},
{1, 10},
{2, 100},
{3, 6}
};
elem_container elemc(begin(elems), end(elems));
// by id
std::cout << "By ID: " << std::endl;
for(auto& x : elemc.get<0>()) {
std::cout << "id: " << x.id << "priority: " << x.priority << std::endl;
}
// by priority
std::cout << "By Priority: " << std::endl;
for(auto& x : elemc.get<1>()) {
std::cout << "id: " << x.id << "priority: " << x.priority << std::endl;
}
return 0;
}