【发布时间】:2011-02-03 18:31:32
【问题描述】:
我正在尝试编写一个可以传递给 std::sort 的仿函数,它将根据向量中对象的比较对表示另一个对象向量的索引的向量进行排序。我不想假设向量中的对象有一个成员 operator
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)));
编译它给我的错误是 2 个重载都不能转换所有参数类型。
【问题讨论】:
-
我认为是因为您的
operator()应该接收两个const T&类型的参数,而您将其设计为接收ULONG。 -
_Pr 是保留标识符;不要使用它。
标签: c++