我想知道是否有办法在std::partial_sort
的随机访问索引上使用boost::partial_sort
或multi_index
。
如果我尝试使用std::patial_sort
我得到编译器错误,暗示迭代器derefence是const因此我无法编译。我知道保持索引的顺序所有multi_index
次迭代都是const迭代器。但是有内部排序函数,但是,在boost multi_index中没有partial_sort。
答案 0 :(得分:2)
随机访问迭代器提供rearrangement,但不提供直接变异。所以,使用代理做到这一点:
<强> Live On Coliru 强>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/random_access_index.hpp>
#include <iostream>
using Record = int; // or your user-defined type, of course
namespace bmi = boost::multi_index;
using Table = bmi::multi_index_container<Record,
bmi::indexed_by<
bmi::random_access<bmi::tag<struct RA_index> >
> >;
int main() {
Table table;
for (Record i : { 1, 7, 4, 8, 4, 3, 4, 6, 1, -3, 31 })
table.push_back(i);
// now the partial sort:
{
std::vector<boost::reference_wrapper<Record const> > tmp(table.begin(), table.end());
std::partial_sort(tmp.begin(), tmp.begin()+8, tmp.end());
// apply back to RA_index
table.get<RA_index>().rearrange(tmp.begin());
}
std::cout << "Partially sorted: ";
std::copy(table.begin(), table.end(), std::ostream_iterator<Record>(std::cout, " "));
}
打印
Partially sorted: -3 1 1 3 4 4 4 6 8 7 31