2

I was wondering if there is a way to use std::partial_sort or boost::partial_sort on multi_index's random access index.

If I try to use std::patial_sort I get compiler errors implying that the iterator derefence is const therefore I cannot compile. I am aware that to keep the order of indexes all multi_index iterations are const iterators.But there are internal sort function, however, no partial_sort in boost multi_index.

Saif Ur Rehman
  • 338
  • 3
  • 14

1 Answers1

2

Random access iterators afford rearrangement, but not direct mutation. So, do it using a proxy:

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, " "));
}

Prints

Partially sorted: -3 1 1 3 4 4 4 6 8 7 31 
sehe
  • 374,641
  • 47
  • 450
  • 633