I’m trying to write a functor that I can pass to std::sort that will sort a vector representing the indicies for another vector of objects based on the comparison of the objects in the vector. Rather than assume that the objects in the vector have a member operator<, I want to pass in a predicate such as I would pass into std::sort if I was sorting the vector of objects directly.
template <class T, class _Pr>
class SortIndexVectorObjectsHelper : public std::binary_function<ULONG, ULONG, bool>
{
ULONG m_ulSize;
std::vector<T> & m_aItems;
BOOL m_bSortAscending;
_Pr m_Comp;
public:
SortIndexVectorObjectsHelper(std::vector<T> & aItems, _Pr Comp) : m_aItems(aItems), m_Comp(Comp), m_ulSize(0)
{
m_ulSize = m_aItems.size();
}
bool operator()( ULONG & rLeft, ULONG & rRight)
{
if (rLeft < m_ulSize && rRight < m_ulSize)
{
T & pLeft = m_aItems[rLeft];
T & pRight = m_aItems[rRight];
if (pLeft && pRight)
{
return m_Comp(pLeft, pRight);
}
}
return false;
}
};
struct SortFooByX: public std::binary_function<CFoo,CFoo, bool>
{
BOOL m_bSortAscending;
SortFooByX(BOOL bSortAscending)
{
m_bSortAscending = bSortAscending;
}
bool operator()( CFoo & _Left, CFoo & _Right)
{
if (m_bSortAscending)
{
if (_Left.X() < _Right.X())
return true;
}
else
{
if (_Left.X() > _Right.X())
return true;
}
return false;
}
};
std::sort(aFooIndicies.begin(), aFooIndicies.end(), SortIndexVectorObjectsHelper<CFoo, std::binary_function<CFoo, CFoo, bool> >(aFoo, SortFooByX(FALSE)));
Compiling this gives me the error that none of the 2 overloads could convert all of the argument types.
The second type argument in
SortIndexVectorObjectsHelperis wrong. The type should beSortFooByX, as shown below:Try this. It should work now.