1st post here...
I'm having some trouble with std::min_element and my code. Basically, what I'm trying to do is a small partial sort of the first N elements of a list (note that partial_sort only works with random access iterators). The thing is, my sorting criteria is a binary predicate that depends on a 3rd varible. Hence, I'm using a functor with an internal reference to my other variable.
However, when I run it it gives an invalid reference/pointer and bails out. I've traced the error to the min_element call. Until then, everything is fine but once it gets inside it my iterators gets invalidated. I know I could do it another way but I was quickly prototyping my program and I want to understand what's happening here. Any ideas?
Aaaanyway, here's the code:
// distance to a reference disk comparison
struct distPred : binary_function<const Disk*,const Disk*,bool>
{
Disk* dr;
bool operator()(const Disk* d1, const Disk* d2) const
{
return ( d1->distanceTo(*dr) < d2->distanceTo(*dr) );
}
distPred(Disk* rPtr) { dr = rPtr; }
};
and the sorting function...
unsigned short
small_sort(DiskList::iterator from,
DiskList::iterator to,
const distPred& cmp,
unsigned short n)
{
DiskList::iterator mit, it;
unsigned short i = 0;
for (; from != to, i < n; ++i, ++from ) {
mit = min_element(from, to, cmp);
ptr_swap(*mit,*from);
}
return i;
}
Feel free to bash my code :blush:
cheers!
Ozz












