Reputation: 81
I have an arr1 of a custom objects but one of the members is arr1.percentChanged I need a second array that stores the index values of arr1 sorted by percentChanged but that leaves the first array untouched.
the percent changed is a double [8.67, -9.64, 14.83, 0.99, -5.33] I initialize arr2 to [0,1,2,3,4] but I cannot figure out how to sort it. i.e. it should be [2,0,3,4,1]. Any help on how to do this would be greatly appreciated.
I think my problem is that my 1st array isn't an array of doubles, but an array of stockObjects. so arr1 is really [obj1,obj2...] but each obj has an obj.percentChanged member. They are sorted in the arr1 by obj.name. I have a second custom object called stockListType that needs a sortPercentageIndex. the stockList object has 1 array that stores all the stockObjects in the order they were read in from a file. It also holds the sortPercentageIndex array. I need a sortByPercentage method to sort the index array in descending order. I can post some code if it helps, but it is part of a much larger program and some classes are subclassed so I was afraid it wouldn't make sense without seeing it all.
Upvotes: 0
Views: 96
Reputation: 10038
Pass a comparator functor to your sort function:
struct comparePercentChanged
{
const double* arr1;
comparePercentChanged( const double* arr1 ): arr1(arr1) { }
bool operator < ( int index1, int index2 ) const
{
return arr1[index1] < arr1[index2];
}
};
std::sort( begin(arr2), end(arr2), comparePercentChanged(arr1) );
Alternately, you can use a lambda:
std::sort( begin(arr2), end(arr2), [const &arr1]( int index1, int index2 ) -> bool
{
return arr1[index1] < arr1[index2];
} );
(This all assumes that arr2 is an array of int indices.)
Upvotes: 1