P
panzhiyong
Hi there! I wonder why there is no such a overload version of sort
function in STL:
template<class RandomAccessIterator, class Pr, class IterSwap>
void sort(
RandomAccessIterator _First,
RandomAccessIterator _Last,
BinaryPredicate _Comp,
IterSwap _Swap
);
It seems that std::sort works only with "simple" element, which has
default constructor and value semantics. So the problem rises when I
want to sort a collection of point coordinates, like:
// sort 2D points, note that I use double(*)[2] to hold points'
coordinates.
void SortPoint(double coords[][2], int n)
{
sort(coords, coords + n, PointLess()); // compile error in
std::swap, require l-value.
}
What I want is somthing like:
void SortPoint(double coords[][2], int n)
{
sort(coords, coords + n, PointLess(), PointSwap());
}
Wish somebody to share his(her) thought about this!
// compare points
class PointLess
{
public:
bool operator() (double* a, double* b)
{
if(abs(a[0] - b[0]) > tolerance)
return a[0] < b[0];
return a[1] < b[1];
}
};
// swap points
class PointSwap
{
public:
void operator() (double* a, double* b)
{
swap(a[0], b[0]);
swap(a[1], b[1]);
}
};
function in STL:
template<class RandomAccessIterator, class Pr, class IterSwap>
void sort(
RandomAccessIterator _First,
RandomAccessIterator _Last,
BinaryPredicate _Comp,
IterSwap _Swap
);
It seems that std::sort works only with "simple" element, which has
default constructor and value semantics. So the problem rises when I
want to sort a collection of point coordinates, like:
// sort 2D points, note that I use double(*)[2] to hold points'
coordinates.
void SortPoint(double coords[][2], int n)
{
sort(coords, coords + n, PointLess()); // compile error in
std::swap, require l-value.
}
What I want is somthing like:
void SortPoint(double coords[][2], int n)
{
sort(coords, coords + n, PointLess(), PointSwap());
}
Wish somebody to share his(her) thought about this!
// compare points
class PointLess
{
public:
bool operator() (double* a, double* b)
{
if(abs(a[0] - b[0]) > tolerance)
return a[0] < b[0];
return a[1] < b[1];
}
};
// swap points
class PointSwap
{
public:
void operator() (double* a, double* b)
{
swap(a[0], b[0]);
swap(a[1], b[1]);
}
};