Sign in to follow this  
Rasmadrak

Advanced sorting (based on external array) = possible?

Recommended Posts

Hi! I'm trying to sort an std::vector based on the value of another array, is this possible? For instance, a regular sort may look like this:
bool sortLess(const MyClass &A, const MyClass &B)
{
   return A.value < B.value;
}


But for this particular solution I would like to something similar to this:
bool sortLess(const int &A, const int &B)
{
   return SomeArrayOfFloats[A] < SomeArrayOfFloats[B];
}


Is this possible? I get an error saying "no matching function for call to `std::list<int, std::allocator<int> >::sort(<unknown type>)'"... Would I be easier off to create a dummy class that has both values and sort that instead? Sound a lot like wasting memory to me... :/ /Robert

Share this post


Link to post
Share on other sites
There are ways to do this. It depends on how your sort criteria array relates to the value array, which you didn't specify.

The most generic way is to implement a specialised sort function for specialised cases tough...

Duplicating all the data temporarily, as you suggested, is probably the worst way to do it.

Share this post


Link to post
Share on other sites
You can :)

All you need to do is define a functional object which refers to your vectors/arrays, instead of a normal function i.e.:


#include <functional> // std::binary_function
#include <vector>

struct my_closure_predicate : std::binary_function<int, int, bool>
{
const std::vector<float>* evn_;
my_closure_predicate(const std::vector<float>& evn)
: evn_(&evn) {}

bool operator()(int lhs, int rhs) const
{
return (*evn_)[lhs] < (*evn_)[rhs];
}
};
//....
#include <list>
std::list<int> my_list_of_ints;
//...
my_list_of_ints.sort(my_closure_predicate(my_array_of_floats));


Don't worry about inheriting from std::binary_function all it does is inherit some nested type aliases (typedef) representing the function's argument and return types.

Share this post


Link to post
Share on other sites
You can make a functor.



struct IndexedCompare : public std::binary_function<int, int, bool> {

const std::vector<YourType> *data;

IndexedCompare(const std::vector<YourType>& data) : data(&data) { }

bool operator()(int left, int right) const
{
return (*data)[left] < (*data)[right];
}
};

// code

std::list<int> list;
std::vector<YourType> data;

list.sort(IndexedCompare(data));



EDIT: You were faster snk_kid :-)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this