Bas Nedermeijer wrote:
Hello,
i am having trouble to use the sort() function of a list<>.
I cannot seem to overload the operator<().
The variables to compare are references, like
Item* itemA;
Item* itemB;
when comparing "itemA < itemB" my overloaded function isnt called. When
the variables are defined;
Item itemA;
Item itemB;
the overloaded function is called.
I hope it is possible for what i want.
Below is my "operator<", also a "const diritem& rhs" didnt resolve my
problem.
int diritem::operator<(const diritem* rhs) const {
printf("%s < %s\n",this->_filename.c_str(), rhs->_filename.c_str());
if ((this->_type==DT_DIR) && (rhs->_type!=DT_DIR)) {
return 1;
}
if ((this->_type!=DT_DIR) && (rhs->_type==DT_DIR)) {
return 0;
}
return (this->_filename < rhs->_filename);
}
Any pointers are welcome!
Kind regards,
Bas Nedermeijer
The list container has a sort member template that takes a binary
predicate to use for sorting. What you need to do is pass in a
predicate that sorts the objects based on pointers to those objects.
The following template may help:
template <typename T>
struct ptr_less
{
bool operator()(T * p1, T * p2)
{
return *p1 < *p2 ;
}
} ;
And, for what it is worth, here is the program I used to test that
template:
template <typename T>
struct ptr_less
{
bool operator()(T * p1, T * p2)
{
return *p1 < *p2 ;
}
} ;
#include <list>
#include <iostream>
#include <algorithm>
void ptr_out(int * p)
{
std::cout << *p << ' ' ;
}
int main()
{
int a[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 } ;
// Add pointers to the list.
std::list<int *v ;
for (std::size_t i = 0; i < sizeof(a)/sizeof(a[0]); ++i)
v.push_back(a+i) ;
// Show the list unsorted.
std::for_each(v.begin(), v.end(), ptr_out) ;
std::cout << std::endl ;
// Sort the list.
v.sort(ptr_less<int>()) ;
// Show the list sorted.
std::for_each(v.begin(), v.end(), ptr_out) ;
std::cout << std::endl ;
}
--
Alan Johnson