我想寫一個函子,我可以傳遞給std :: sort,它會根據向量中對象的比較結果來排序表示另一個對象向量的向量的向量。而不是假設向量中的對象具有成員操作符<,我想傳入一個謂詞,比如我將它傳遞到std :: sort,如果我直接對對象向量進行排序。傳遞函子給一個函子
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`。 – 2011-02-03 18:41:26
_Pr是保留的標識符;不要使用它。 – 2011-02-03 18:45:31