Re: how to parallel sort?
nandor.sieben@gmail.com wrote:
You can easily use STL. Just create the resulting vector with indices
from 0 to n and sort it using as sort criteria the values of the other
vectors index. Give it some time to learn it, then come back if you
get stuck.
/Peter
This sounds like what I'd like to do but I don't know where to start
on changing the sort criteria. Do I need to write a function object
that has the other vector as extra input?
Yes.
I have a feeling this is
just a one liner sort command but it's beyond my knowledge of STL.
Consider:
#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>
template < typename Sequence >
class ForwardCompare {
Sequence const & the_sequence;
public:
ForwardCompare ( Sequence const & ref )
: the_sequence ( ref )
{}
bool operator() ( typename Sequence::size_type lhs,
typename Sequence::size_type rhs ) const {
return ( the_sequence[lhs] < the_sequence[rhs] );
}
};
template < typename Sequence >
ForwardCompare< Sequence > make_ForwardCompare ( Sequence const & seq ) {
return ( ForwardCompare< Sequence >( seq ) );
}
int main ( void ) {
std::vector< int > value;
value.push_back( 2 );
value.push_back( 1 );
value.push_back( 5 );
value.push_back( 4 );
std::vector< int > index;
for ( int i = 0; i < value.size(); ++i ) {
index.push_back( i );
}
std::sort( index.begin(), index.end(), make_ForwardCompare( value ) );
std::copy( index.begin(), index.end(),
std::ostream_iterator< int >( std::cout, " " ) );
std::cout << '\n';
}
It would be a one-liner, if lambda allowed for:
std::sort( index.begin(), index.end(), value[_1] < value[_2] );
However, I think that does not work (and as long as the subscript operator
is required to be a member function, I don't see a way to implement lambda
so that it would work).
Best
Kai-Uwe Bux