Re: STL sort with derived class
mweltin@gmail.com wrote:
I have a derived class that extends a base class by adding a float
member. The strange part is when I use the STL sort algorithm on a
vector of derived classes, only hte float member is sorted.
For example assume a vector containg three derived class objects
called blah.
blah[0] { ... int one = 7 , int two = 5, int three =8 , float five =
1}
blah[1] { ... int one = 6 , int two = 6, int three =4 , float five =
0}
blah[2] { ... int one = 5 , int two = 7, int three =5 , float five =
3}
both the derived class and base class have a copy constructor and the
assignment operator overloaded. The derived class also overloads the
binary operators '<', '>', and '==', al of which define their return
value based only on the float member (five).
After a sort I end up with
blah[0] { ... int one = 7 , int two = 5, int three =8 , float five =
0}
blah[1] { ... int one = 6 , int two = 6, int three =4 , float five =
1}
blah[2] { ... int one = 5 , int two = 7, int three =5 , float five =
3}
But what I expect and would like is
blah[0] { ... int one = 6 , int two = 6, int three =4 , float five =
0}
blah[1] { ... int one = 7 , int two = 5, int three =8 , float five =
1}
blah[2] { ... int one = 5 , int two = 7, int three =5 , float five =
3}
I'm having a devil of a time trying to figure this out.
thank you for your time,
Markus
Without sample code to demonstrate the problem it is difficult to give
much or any help with your problem,
It would appear to me the operator <() for the derived class only
compares the float member which is why the sort is done against the
float. To sort based on both you will need comparison function which can
be passed to the stl::sort() which does the required comparison.
JB