lok wrote in news: om:
>
> i modified the code as follow:
> ==================================
Firstly my appologiess, I gave bad advise, makeing operator() virtual
was not a good idea as functors are mostly passed by value (so that
an ordinary function is also a functor), so slicing would occur
and what gets passed to std::sort is the base class with the
original operator ().
The following is a fix (of sorts) but it has no real advantage
over using a simple function pointer. Though it could if you need
to make the functor more complex.
#include <vector>
#include <functional>
#include <algorithm> // std::sort()
#include <string>
using std::string;
template <class T1, class T2 >
class CPairMapping
{
public:
typedef std:

air<T1, T2 > ValuePair_t;
typedef std::vector< ValuePair_t > ValueList_t;
class ValuePair_IsLess :
std::binary_function<
ValuePair_t const &, ValuePair_t const &, bool
>
{
protected:
typedef
bool (*m_cmp_t)(
ValuePair_t const &lhs_, ValuePair_t const & rhs_
)
;
m_cmp_t m_cmp;
public:
ValuePair_IsLess( m_cmp_t cmp ) : m_cmp( cmp ) {}
bool operator() (
ValuePair_t const &lhs_, ValuePair_t const &rhs_
) const
{
return m_cmp( lhs_, rhs_ );
}
};
void SortAscend( ValuePair_IsLess isLess_ )
{
std::sort( Map.begin(), Map.end(), isLess_ );
}
protected:
ValueList_t Map;
};
typedef CPairMapping< string, string > STR2STRMap;
class STR2STRMap_IsLess: public STR2STRMap::ValuePair_IsLess
{
static bool cmp(
STR2STRMap::ValuePair_t const &lhs_,
STR2STRMap::ValuePair_t const &rhs_
)
{
return lhs_.first.size() < rhs_.first.size(); // #error line
// note the lack of .first().size() ..
}
typedef STR2STRMap::ValuePair_IsLess base_t;
public:
STR2STRMap_IsLess() : base_t( cmp ) {}
};
int main()
{
STR2STRMap a;
STR2STRMap_IsLess isLess;
a.SortAscend( isLess );
return 0;
}
Here's a simple function version, there is *alot* less cruft if
you really don't need it.
#include <vector>
#include <functional>
#include <algorithm> // std::sort()
#include <string>
using std::string;
template <class T1, class T2 >
class CPairMapping
{
public:
typedef std:

air<T1, T2 > ValuePair_t;
typedef std::vector< ValuePair_t > ValueList_t;
typedef bool (*ValuePair_IsLess)(
ValuePair_t const &lhs_, ValuePair_t const & rhs_
);
void SortAscend( ValuePair_IsLess isLess_ )
{
std::sort( Map.begin(), Map.end(), isLess_ );
}
protected:
ValueList_t Map;
};
typedef CPairMapping< string, string > STR2STRMap;
bool STR2STRMap_IsLess(
STR2STRMap::ValuePair_t const &lhs_,
STR2STRMap::ValuePair_t const & rhs_
)
{
return lhs_.first.size() < rhs_.first.size();
}
int main()
{
STR2STRMap a;
//STR2STRMap_IsLess isLess;
a.SortAscend( STR2STRMap_IsLess );
return 0;
}
Rob.
--
http://www.victim-prime.dsl.pipex.com/