Re: why std::sort take no template parameter to swap?
On Nov 27, 5:49 am, panzhiyong <panzhiyon...@gmail.com> wrote:
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
);
Because the correct solution here is to provide an appropriate
swap action for the object in question.
It seems that std::sort works only with "simple" element, which has
default constructor and value semantics.
It definitly requires value semantics. You can't move elements
around unless they have value semantics, and you can't sort
unless you can move elements around. There's no requirement
for a default constructor, however. And the elements can be as
complicated as you want: you can sort an array of std::map, for
example (provided you define an appropriate ordering criteria).
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.
}
C style arrays are broken. In C++, this would probably be
written more like:
void SortPoint( std::vector< Point >& coords )
{
std::sort( coords.begin(). coords.end(), PointLess() ) ;
}
There are very few practical reasons to ever use a C style
array, and from what I've seen, boost::array subsumes them all.
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!
Write it correctly, using a Point class, and it should work.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34