Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does STL or BOOST provide any clean way to get the sort order without reordering original sequence?

I'd like to find the sort order of a vector, for example, without reordering the vector.

I can think of several ways to do this, I'm wondering if I'm missing some built-in STL or BOOST way to do this.

I imagine if the functionality were available the code would end up looking something like this:

std::vector<float> unsortedSeq;
unsortedSeq.push_back( 1.1 );
unsortedSeq.push_back( 1.0 );
unsortedSeq.push_back( 0.5 );
unsortedSeq.push_back( 1.2 );
unsortedSeq.push_back( 1.15 );

std::list<std::size_t> sortOrder;

std::sort_indices( unsortedSeq.begin(), unsortedSeq.end(), sortOrder.begin() );

BOOST_FOREACH( std::size_t index, sortOrder )
{
    std::cout << index << "\n"
}



2
1
0
4
3

Anyone know any STL or BOOST-sims that would do what I'm asking about as simply as shown?

like image 224
Catskul Avatar asked Dec 17 '22 12:12

Catskul


1 Answers

std::vector<float> v;
// filled somewhere else

std::vector<std::size_t> indices(v.size());
// iota is from <numeric>, C++0x
std::iota(indices.begin(), indices.end(), 0);

std::sort(indices.begin(), indices.end(), [&v](std::size_t left, std::size_t right)
{
    return v[left] < v[right];
});
like image 112
Luc Danton Avatar answered Dec 19 '22 03:12

Luc Danton