Re: STL algorithms & operator overloading
From: Francis Glassborow (francis_at_robinton.demon.co.uk)
Date: 03/01/04
- Next message: James Dennett: "Re: [C++] virtual destructor behavior"
- Previous message: James Dennett: "Re: Awainting Return Keypress"
- In reply to: Sumek: "STL algorithms & operator overloading"
- Next in thread: Leor Zolman: "Re: STL algorithms & operator overloading"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sun, 29 Feb 2004 23:24:52 +0000
In message <eun440tf1929oessnak9tdp1h2plrunvjf@4ax.com>, Sumek
<sumek@o2.pl> writes
>Hi!
> I'm trying to sort vector of pointers to classes using STL
>algorithms. I know that I need to overload < operator, so I've written
>something like this
No, I doubt that overloading operator < will help here. What you need to
do is to write a suitable function to compare two pointers to object by
comparing the objects.
bool compare(mytype * first, mytype * second){
return *first < *second;
}
// this assumes that mytype has an operator <, if it does not
// just do whatever computation is needed to determine which
// of the two instances should come first
now given:
vector<mytype *> vec;
// put something into vec
sort(vec.begin(), vec.end(), compare);
will now sort the contents of vec on the basis of the comparison of the
objects pointed to by the rule encapsulated in compare()
The important part to note is that sort() has three parameters, the last
one is defaulted to operator< for the type of object that the iterator
args of the first two are identifying. However the third parameter can
be given an explicit argument which needs to be a suitable function (or
function object) that returns true if the first argument (of the compare
function) is less than the second.
-- Francis Glassborow ACCU Author of 'You Can Do It!' see http://www.spellen.org/youcandoit For project ideas and contributions: http://www.spellen.org/youcandoit/projects
- Next message: James Dennett: "Re: [C++] virtual destructor behavior"
- Previous message: James Dennett: "Re: Awainting Return Keypress"
- In reply to: Sumek: "STL algorithms & operator overloading"
- Next in thread: Leor Zolman: "Re: STL algorithms & operator overloading"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|